0

我有一个特定的json:

[
    {
        "id"        : 42422422,
        "created"   : 1329684013,
        "name"          : "Test"
    },
    {
        "id"        : 42422423,
        "created"   : 1329684015,
        "name"          : "Test 123"
    },
        {
          ...
        }
]

解析这个没问题,但是当网络服务器出错时,这个 JSON 被返回:

{
    "error" : {
        "code"      : "511",
        "message"   : "JSON error",
        "extra" : {
            "some"      : "text",
            "someextra" : "text"
        }
    }
}

我试过用这个:

if ([jsonArray valueForKey:@"error"] != nil) {

但这不起作用,因为如果我输出它的值,它就是一个'null's'数组

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

我像这样解析 JSON:

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

responseData 来自 NSURLConnection 的 connectionDidFinishLoading 方法。

4

5 回答 5

7

您应该首先检查您的结果是数组还是字典。

if ([jsonArray isKindOfClass:[NSArray class]]) {
     //process results
} else if ([jsonArray isKindOfClass:[NSDictionary class]]) {
    NSDictionary *errorInfo = [(NSDictionary *)jsonArray objectForKey:@"error"];
    //handle error...
}
于 2012-11-23T07:49:27.433 回答
2

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

获取 Nextbelt 的演示

下载 JSON 框架

 NSString *appurl =[NSString stringWithFormat:@"your link"];
 appurl = [appurl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
 NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:appurl]];
 NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse: nil error: nil ];
 NSString  *returnString = [[NSString alloc] initWithData:returnData encoding: NSUTF8StringEncoding];
 NSMutableDictionary *deletdict=[returnString JSONValue];
 if([[deletdict objectForKey:@"success"] isEqualToString:@"False"])
    {
        NSLog(@"Unsuccess...");

    }
 else
    {
        NSLog(@"success...");
    }

AND 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];
于 2013-11-22T05:43:10.253 回答
0

对于非错误 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"]];
于 2012-11-23T08:21:06.940 回答
0
-(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];
}
于 2014-12-11T07:17:00.590 回答
-2

使用[jsonArray objectForKey:@"error"]而不是valueForKey

于 2012-11-23T07:44:52.553 回答