【发布时间】:2014-03-20 19:00:17
【问题描述】:
我需要从下面给定从网站检索的 json 对象中分离子人、姓名、年龄、家庭地址、办公室地址
{“人”:
[{"subperson":{"home":{"id":"kljljk"},"name":"person3","age":"18","addr":{"home addr": "ksdjr","office addr":"kjshdg"}}}]}
尝试了 nsjsonserialization、sbjson 和 touchJSON api。返回一个字典,其中人是键,其他都是值(代码下方指定的 json 字符串格式) 我的代码:
NSURLRequest *urlreq = [NSURLRequest requestWithURL:url];
NSData *response = [NSURLConnection sendSynchronousRequest:urlreq returningResponse:nil error:nil];
[webviv loadRequest:urlreq];
SBJsonParser *jsonparser = [SBJsonParser new];
NSDictionary *json = [jsonparser objectWithData:response];
NSLog(@"%@\n", json);
for(id key in json)
{
NSLog(@"%@=%@",key,[json objectWithKey: key]);
}
//output is
person = (everythingelse starting with [, can't separate name and other required things)
//using NSJSONSerialization
if ([NSJSONSerialization JSONObjectWithData:response options:0 error:&error])
{
NSLog(@"json");
}
NSData *pTL = [NSJSONSerialization JSONObjectWithData:response options:0 error:&error];
NSLog(@"%@",pTL);
//Output is the same
//for(int i=0;i<[pTL count];i++)
//{
//NSLog(@"%d",i);
//}
//even with for loop the output is the same
【问题讨论】:
-
你确定吗?例如, json[@"person"][0][@"subperson"] 返回什么? NSJSONSerialization 确实会递归到 JSON 中。
-
不明白你在这里说什么,但是当我使用 nslog(json[@"person"][0][@"subperson"]) 运行时它显示错误并且当我运行 nslog( json[0][@"subperson"]) 并且还显示 json[@person][0] 的错误
-
解析成功....谢谢大家
标签: ios objective-c json