[英]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.