簡體   English   中英

在iOS APP中解析JSON

[英]Parse JSON in iOS APP

我正在使用iOS應用程序,並且必須解碼json響應。

響應數據如下所示:

[{"owner":"123456789","id":"1","liked":"0","unliked":"0","nickname":"jack","filename":"name_image.jpg","user":null,"image":null,"type":null}]

這是我的應用程序中的代碼:

//parse out the json data
NSError* error;
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];            
NSString *owner = [json valueForKey:@"owner"];      
NSLog(@"\n\nowner: %@", owner);

在日志中,我看到以下內容:

owner: (
    3402379524
)

如何去除圓括號並獲得正確的價值? 我也嘗試使用這個:

NSDictionary *owner_image = [json objectForKey:@"owner"];   

但是應用程序崩潰了。

您有字典數組,因此需要首先獲取數組對象,然后才能從字典獲取值。

NSArray* json   = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSString *owner = json[0][@"owner"];  
NSLog(@"\n\nowner: %@", owner);

為了更好地了解結構,請參見下圖。

在此處輸入圖片說明

 NSDictionary *owner_image = [((NSDictionary *)[json objectForIndex:0]) objectForKey:@"owner"];  

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM