[英]Parsing JSON with Objective-C
For my project I have built my own api using PHP. 对于我的项目,我使用PHP构建了自己的api。 The result of json encoding basically gives me an array of entries like below
json编码的结果基本上给了我如下所示的条目数组
{"terms":[
{"term0":
{"content":"test id",
"userid":"100","translateto":null,
"hastranslation":"0",
"created":"2011-10-19 16:54:57",
"updated":"2011-10-19 16:55:58"}
},
{"term1":
{"content":"Initial content",
"userid":"3","translateto":null,
"hastranslation":"0",
"created":"2011-10-19 16:51:33",
"updated":"2011-10-19 16:51:33"
}
}
]
}
However, I've been having problems working with NSMutableDictionary and extracting "content" in Objective-C. 但是,在使用NSMutableDictionary和在Objective-C中提取“内容”时遇到了问题。
- (void) connectionDidFinishLoading:(NSURLConnection *)connection {
[connection release];
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
[responseData release];
NSMutableDictionary *JSONval = [responseString JSONValue];
[responseString release];
if (JSONval != nil) {
NSMutableDictionary *responseDataDict = [JSONval objectForKey:@"terms"];
if (responseDataDict!= nil) {
for (id key in responseDataDict) {
NSString *content = [[responseDataDict objectForKey:key]objectForKey:@"content"];
[terms addObject:content];
textView.text = [textView.text stringByAppendingFormat:@"\n%@", content];
}
button.enabled = YES;
}
}
} }
Where NSLog spits out error when I send objectForKey to responseDataDict, which is a __NSArrayM according to the log. 当我将objectForKey发送到responseDataDict(根据日志为__NSArrayM)时,NSLog吐出错误的地方。
What did I do wrong here? 我在这里做错了什么?
NSMutableDictionary *responseDataDict = [JSONval objectForKey:@"terms"];
NSMutableDictionary * responseDataDict = [JSONval objectForKey:@“ terms”];
But the value of "terms"
isn't a dictionary; 但是
"terms"
的价值不是字典。 it's an array. 这是一个数组。 Note the square brackets in your JSON string.
请注意JSON字符串中的方括号。 You should use:
您应该使用:
NSArray *terms = [JSONval objectForKey:@"terms"];
instead. 代替。
Note that each term in the array is an object (a dictionary) containing a single name (key) whose corresponding value (object) is, in turn, another object (dictionary). 请注意,数组中的每个术语都是一个对象(字典),其中包含一个名称(键),其对应的值(对象)又是另一个对象(字典)。 You should parse them as:
您应该将它们解析为:
// JSONval is a dictionary containing a single key called 'terms'
NSArray *terms = [JSONval objectForKey:@"terms"];
// Each element in the array is a dictionary with a single key
// representing a term identifier
for (NSDictionary *termId in terms) {
// Get the single dictionary in each termId dictionary
NSArray *values = [termId allValues];
// Make sure there's exactly one dictionary inside termId
if ([values count] == 1) {
// Get the single dictionary inside termId
NSDictionary *term = [values objectAtIndex:0];
NSString *content = [term objectForKey:@"content"]
…
}
}
Add further validation as needed. 根据需要添加进一步的验证。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.