iphonesdk上的JSON解析

iphonesdk上的JSON解析,iphone,objective-c,ios,xcode,json,Iphone,Objective C,Ios,Xcode,Json,我有一个特定的json: [ { "id" : 42422422, "created" : 1329684013, "name" : "Test" }, { "id" : 42422423, "created" : 1329684015, "name" : "Test 123" },

我有一个特定的json:

[
    {
        "id"        : 42422422,
        "created"   : 1329684013,
        "name"          : "Test"
    },
    {
        "id"        : 42422423,
        "created"   : 1329684015,
        "name"          : "Test 123"
    },
        {
          ...
        }
]
解析此goed OK,但当Web服务器出现错误时,将返回此JSON:

{
    "error" : {
        "code"      : "511",
        "message"   : "JSON error",
        "extra" : {
            "some"      : "text",
            "someextra" : "text"
        }
    }
}
我试过用这个:

if ([jsonArray valueForKey:@"error"] != nil) {
但这不起作用,因为如果我输出它的值,它是一个“null”数组

我怎么检查这个?(我知道我可以使用
NSRange
,但我认为必须有更好的方法,对吗

我像这样解析JSON:

NSDictionary *jsonArray = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error: &e]; 

responseData来自NSURLConnection的ConnectionIDFinishLoading方法。

使用
[jsonArray objectForKey:@“error”]
而不是
valueForKey
您应该先检查结果是数组还是字典

if ([jsonArray isKindOfClass:[NSArray class]]) {
     //process results
} else if ([jsonArray isKindOfClass:[NSDictionary class]]) {
    NSDictionary *errorInfo = [(NSDictionary *)jsonArray objectForKey:@"error"];
    //handle error...
}

对于非错误JSON负载,您有一个顶级数组(由开头[]注明),而对于错误JSON负载,您没有

{
    "error" : {
        "code"      : "511",
        "message"   : "JSON error",
        "extra" : {
            "some"      : "text",
            "someextra" : "text"
        }
    }
}
错误代码是嵌套字典对象,因此您可以使用以下方法对其进行分析:

NSDictionary* json = [NSJSONSerialization
                              JSONObjectWithData:responseData
                              options:kNilOptions
                              error:&error];

NSString *errorCode = [NSString stringWithFormat:@"%@",[(NSDictionary*)[json objectForKey:@"error"]objectForKey:@"code"]];

检查下面的链接并简单地解析Json

这是Post方法吗

NSString *post =[NSString stringWithFormat:@"AgencyId=STM&UserId=1&Type=1&Date=%@&Time=%@&Coords=%@&Image=h32979`7~U@)01123737373773&SeverityLevel=2",strDateLocal,strDateTime,dict];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@"%d",[postData length]];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://google/places"]]];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postData];
NSError *error;
NSURLResponse *response;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *str=[[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];

NSMutableArray *SubLiveArray=[str JSONValue];

show use您用来解析JSON的objC代码..我不明白为什么KVC for error会返回数组…@Daij Djan阅读
NSArray
关于
valueForKey:
的文档-它返回所有元素的
valueForKey:
结果数组(使用
[NSNull]
如果为元素返回了
nil
)。2012-11-23 09:03:39.164 MyApp[992:c07](“”、“”、“”、“”、“”、“”、“”、“”、“”、“”、“”、“”、“”、“”、“”、“”、“”、“”、“”、“”、“”、“”)这是NSLog的输出(@“%@”,[jsonArray valueForKey:@“error”])您好,您可以对这种类型的null设置条件。.我也遇到了同样的问题。.如果([str isKindOfClass:[NSNull class]])或chk myanswer@Mehul我不知道他在每一个案件中都这么做了..nsarray上的KVC当然是坏的,我想(愚蠢的)他这样做只是为了万一他拿回一本nsdictionary!对于一本不重要的字典..为什么?:)如果数组实际上是一个数组而不是一本字典(如果它是一本字典,它不会有什么区别),那么它将崩溃@omz你是对的,我没有考虑到JSON响应的结构是不同的。我用NSDictionary*jsonArray=[NSJSONSerialization JSONObjectWithData:responseData选项:NSJSONReadingMutableContainers错误:&e]加载jsonArray;所以我认为它总是一个NSDictionary。问题是,当你试图获取objectForKey:@“错误”它找不到它,应用程序崩溃…不,仅仅因为你将指针声明为字典并不意味着它实际上包含字典。
JSONObjectWithData:…
的返回类型是
id
,因此它基本上可以包含任何内容(尽管根据文档,它始终是
NSArray
NSDictionary
)。
NSString *post =[NSString stringWithFormat:@"AgencyId=STM&UserId=1&Type=1&Date=%@&Time=%@&Coords=%@&Image=h32979`7~U@)01123737373773&SeverityLevel=2",strDateLocal,strDateTime,dict];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@"%d",[postData length]];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://google/places"]]];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postData];
NSError *error;
NSURLResponse *response;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *str=[[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];

NSMutableArray *SubLiveArray=[str JSONValue];
-(void)SerchpageApicall
{
    NSString *main_url=@"yourlink";
    NSString *appurl=[NSString stringWithFormat:@"%@&address=%@",main_url,_txt_Search_address.text];

    appurl = [appurl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURL *url=[NSURL URLWithString:appurl];
    NSURLRequest* requestVersion = [NSURLRequest requestWithURL:url
                                                    cachePolicy:NSURLRequestReloadIgnoringCacheData
                                                timeoutInterval:5.0];
    NSHTTPURLResponse* response = nil;
    NSError* error = nil;
    NSData *returnData = [NSURLConnection sendSynchronousRequest:requestVersion returningResponse:&response error:&error ];
    NSString  *returnString = [[NSString alloc] initWithData:returnData encoding: NSUTF8StringEncoding];
    NSMutableDictionary *dict=[returnString JSONValue];
}