簡體   English   中英

在iOS上解析json數組

[英]Parse json array on iOS

我有以下JSON數據:

[{"id":"value","first_name":"value","last_name":"value"},
 {"id":"value","first_name":"value","last_name":"value"},
 {"id":"value","first_name":"","last_name":""}]

然后我實現我的代碼:

NSError *err;
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://abcd.com/index.php?r=WS/Employee"]];
NSData *dataFromUrl = [NSData dataWithContentsOfURL:url];
NSMutableArray *array = [NSJSONSerialization JSONObjectWithData:dataFromUrl options: NSJSONReadingMutableContainers error:&err];

if (err)
    NSLog(@"JSONObjectWithData error: %@", err);

為此,我收到以下錯誤消息:

JSONObjectWithData錯誤:錯誤域= NSCocoaErrorDomain代碼= 3840“操作無法完成。(可可錯誤3840。)”(JSON文本不是以數組或對象開頭,並且沒有允許設置片段的選項。)UserInfo = 0x9c900f0 {NSDebugDescription = JSON文本不是以數組或對象開頭,並且沒有允許設置片段的選項。}

請幫助我獲取這些數據。

我認為您應該在請求標頭中添加更多內容。 嘗試將NSData轉換為NSString並查看適合您的內容

試試這個代碼...。

NSURL * url =[NSURL URLWithString:getDataURL];
NSData * data=[NSData dataWithContentsOfURL:url];

json =[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];

我通過替換來自我的PHP文件中的請求標頭來解決此問題

echo "<meta charset=\"utf-8\">";

 ob_start();
 header('Content-type: application/json');
NSError *err;
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://abcd.com/index.php?r=WS/Employee"]];
NSData *dataFromUrl = [NSData dataWithContentsOfURL:url];
NSMutableArray *array = [NSJSONSerialization JSONObjectWithData:dataFromUrl options:     NSJSONReadingMutableContainers error:&err];

if (err)
   NSLog(@"JSONObjectWithData error: %@", err);

只要改變你的路線

NSMutableArray *array = [NSJSONSerialization JSONObjectWithData:dataFromUrl options:     NSJSONReadingMutableContainers error:&err];

NSJSONSerialization *jsonData = [NSJSONSerialization JSONObjectWithData:dataFromUrl options:     NSJSONReadingMutableContainers error:&err];
NSMutableArray *array = [NSMutableArray arrayWithArray:(NSArray *)jsonData];
NSLog(@"Success:%@", array);

暫無
暫無

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

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