嗨我有以下需要解析的json,但是,我正在努力解析内部数组。我目前只打印每个内部数组,但我想打印说每个标题并将标题添加到数组。谢谢你的帮助!
JSON
{"nodes":[{
"node":{
"nid":"1420857",
"title":"Title 1",
"votes":"182",
"popular":"True",
"teaser":"Teaser 1"
}},
{"node":{
"nid":"1186152",
"title":"Title 2",
"votes":"140",
"popular":"True",
"teaser":"Teaser 2"
}},
{"node":{
"nid":"299856",
"title":"Title 3",
"votes":"136",
"popular":"True",
"teaser":"Teaser 3"
}}
]}
Json Parser
NSError *error = nil;
NSData *jsonData = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://www.somefilename.json"]];
if (jsonData) {
id jsonObjects = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];
if (error) {
NSLog(@"error is %@", [error localizedDescription]);
return;
}
NSArray *keys = [jsonObjects allKeys];
for (NSString *key in keys) {
NSLog(@"%@", [jsonObjects objectForKey:key]);
}
} else {
// Handle Error
}
答案 0 :(得分:1)
只是强调它:
NSArray *nodes = (NSArray*)[jsonObjects objectForKey:@"nodes"];
for (NSDictionary *node in nodes){
// do stuff...
}
返回id
(如-[objectForKey:]
和-[objectAtIndex:]
)的方法可以返回任何objective-c对象。您需要提前知道要对其进行类型转换以对其执行适当的操作。 JSON转换为NSObject等价物:
object
- > NSDictionary
array
- > NSArray
string
- > NSString
number
- > NSNumber
boolean
- > NSNumber
float
- > NSNumber
null
- > NSNull
要区分各种NSNumbers,您必须调用相应的类型方法:-[intValue]
,-[boolValue]
,-[floatValue]
。查看NSNumber docs了解详情。
答案 1 :(得分:0)
您可以使用我的方法进行json解析,
解析方法:
-(void)jsonDeserialize:(NSString *)key fromDict:(id)content completionHandler:(void (^) (id parsedData, NSDictionary *fromDict))completionHandler{
if (key==nil && content ==nil) {
completionHandler(nil,nil);
}
if ([content isKindOfClass:[NSArray class]]) {
for (NSDictionary *obj in content) {
[self jsonDeserialize:key fromDict:obj completionHandler:completionHandler];
}
}
if ([content isKindOfClass:[NSDictionary class]]) {
id result = [content objectForKey:key];
if ([result isKindOfClass:[NSNull class]] || result == nil) {
NSDictionary *temp = (NSDictionary *)content;
NSArray *keys = [temp allKeys];
for (NSString *ikey in keys) {
[self jsonDeserialize:key fromDict:[content objectForKey:ikey] completionHandler:completionHandler];
}
}else{
completionHandler(result,content);
}
}
}
方法调用:
NSData *content = [NSData dataWithContentsOfFile:[[NSBundle mainBundle]pathForResource:@"Sample" ofType:@"json"]];
NSError *error;
//获取序列化的json数据......
id dictionary = [NSJSONSerialization JSONObjectWithData:content options:NSJSONReadingMutableContainers error:&error];
//获取名为 GetInfo
的密钥的数据
[self jsonDeserialize:@"GetInfo" fromDict:dictionary completionHandler:^(id parsedData, NSDictionary *fromDict) {
NSLog(@"%@ - %@",parsedData,fromDict);
}];