我正在尝试从 nsdata 类中获取值但不起作用。
这是我的 JSON 数据。
{
"count": 3,
"item": [{
"id": "1",
"latitude": "37.556811",
"longitude": "126.922015",
"imgUrl": "http://175.211.62.15/sample_res/1.jpg",
"found": false
}, {
"id": "3",
"latitude": "37.556203",
"longitude": "126.922629",
"imgUrl": "http://175.211.62.15/sample_res/3.jpg",
"found": false
}, {
"id": "2",
"latitude": "37.556985",
"longitude": "126.92286",
"imgUrl": "http://175.211.62.15/sample_res/2.jpg",
"found": false
}]
}
这是我的代码
-(NSDictionary *)getDataFromItemList
{
NSData *dataBody = [[NSData alloc] initWithBytes:buffer length:sizeof(buffer)];
NSDictionary *iTem = [[NSDictionary alloc]init];
iTem = [NSJSONSerialization JSONObjectWithData:dataBody options:NSJSONReadingMutableContainers error:nil];
NSLog(@"id = %@",[iTem objectForKey:@"id"]);
//for Test
output = [[NSString alloc] initWithBytes:buffer length:rangeHeader.length encoding:NSUTF8StringEncoding];
NSLog(@"%@",output);
return iTem;
}
如何访问 JSON 中的每个值?请帮助我。
最佳答案
看起来像这样..
NSString *jsonString = @"your json";
NSData *JSONdata = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSError *jsonError = nil;
if (JSONdata != nil) {
//this you need to know json root is NSDictionary or NSArray , you smaple is NSDictionary
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:JSONdata options:0 error:&jsonError];
if (jsonError == nil) {
//every need check value is null or not , json null like ( "count": null )
if (dic == (NSDictionary *)[NSNull null]) {
return nil;
}
//every property you must know , what type is
if ([dic objectForKey:@"count"] != [NSNull null]) {
[self setCount:[[dic objectForKey:@"count"] integerValue]];
}
if ([dic objectForKey:@"item"] != [NSNull null]) {
NSArray *itemArray = [dic objectForKey:@"item"]; // check null if need
for (NSDictionary *itemDic in itemArray){
NSString *_id = [dic objectForKey:@"id"]; // check null if need
NSNumber *found = (NSNumber *)[dic objectForKey:@"found"];
//.....
//.... just Dictionary get key value
}
}
}
}
关于ios - 如何从 xcode 4.2 中的 nsstring 或 byte 获取 JSON 数组数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11134850/