![](/img/trans.png)
[英]JSON API Error- The data couldn’t be read because it is missing.- in iOS, swift
[英]Couldn't parse data using Json on IOS 5
我尝试用ios 5上的json获取一些数据但是我失败了......有人可以帮助我并告诉我为什么它没有成功。 这是我的实现代码
定义:
#define kBgQueue dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0) //1
#define kLatestKivaLoansURL [NSURL URLWithString:@"http://jaksport.com/jarray.php"] //2
然后在viewdidload中:
NSData* data = [NSData dataWithContentsOfURL:
kLatestKivaLoansURL];
[self performSelectorOnMainThread:@selector(fetchedData:)
withObject:data waitUntilDone:YES];
这是功能:
- (void)fetchedData:(NSData *)responseData {
//parse out the json data
NSError* error;
NSDictionary* json = [NSJSONSerialization
JSONObjectWithData:responseData //1
options:kNilOptions
error:&error];
NSArray* key = [json objectForKey:@"price"]; //2
NSLog(@"value: %@", key); //3
}
这是json文件:
{
"prices":
{
"price":[
{
"id":1,
"name":"Rosie Gradas",
"beer":4.5,
"cider":4.5,
"guinness":4
},
{
"id":2,
"name":"Wicked Wolf",
"beer":5,
"cider":4.5,
"guinness":4
},
{
"id":3,
"name":"Cafe Posh",
"beer":6,
"cider":5.5,
"guinness":5.5
},
{
"id":4,
"name":"My House",
"beer":16,
"cider":15.5,
"guinness":15.5
}
]
}
}
nslog始终打印出空值
错误在于如何访问JSON中的对象:
{
"prices":
{
"price":[
{
"id":1,
"name":"Rosie Gradas",
"beer":4.5,
"cider":4.5,
"guinness":4
}
}
给定类似JSON来访问价格数组,您可以使用这样的语法
NSArray *price = [[json objectForKey:@"prices"]objecForkey:@"price"];
检查Web浏览器中的URL,您的URL不是正确的JSON。
JSON验证链接: JSON验证
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.