在iPhone SDK上进行JSON解析 [英] JSON parsing on iPhone SDK
本文介绍了在iPhone SDK上进行JSON解析的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个json:
[
{
"id" : 42422422,
"created" : 1329684013,
"name" : "Test"
},
{
"id" : 42422423,
"created" : 1329684015,
"name" : "Test 123"
},
{
...
}
]
解析此问题,但是当网络服务器出错时,会返回此JSON:
Parsing this goed OK, but when the webserver has an error, this JSON is returned:
{
"error" : {
"code" : "511",
"message" : "JSON error",
"extra" : {
"some" : "text",
"someextra" : "text"
}
}
}
我试过这个:
if ([jsonArray valueForKey:@"error"] != nil) {
但是这不起作用,因为如果我输出它的值'一个'null'的数组
but that doesn't work, because if I output the value of that it's an array of 'null's'
我该如何检查? (我知道我可以使用 NSRange
,但我认为必须有更好的方法吗?
How can I check this? (I know I can use NSRange
, but I think there has to be a better way right?
我解析像这样的JSON:
I parse the JSON like this:
NSDictionary *jsonArray = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error: &e];
responseData来自NSURLConnection的connectionDidFinishLoading方法。
responseData comes from the connectionDidFinishLoading method of NSURLConnection.
推荐答案
您应首先检查您的结果是数组还是字典。
You should check if your result is an array or a dictionary first.
if ([jsonArray isKindOfClass:[NSArray class]]) {
//process results
} else if ([jsonArray isKindOfClass:[NSDictionary class]]) {
NSDictionary *errorInfo = [(NSDictionary *)jsonArray objectForKey:@"error"];
//handle error...
}
这篇关于在iPhone SDK上进行JSON解析的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文