简体   繁体   中英

JSON parsing on iPhone SDK

I have a certain json:

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

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"
        }
    }
}

I've tried using this:

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

but that doesn't work, because if I output the value of that it's an array of 'null's'

How can I check this? (I know I can use NSRange , but I think there has to be a better way right?

I parse the JSON like this:

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

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...
}

Check this below link and simply parse Json.

Get Demo of Nextbelt

Download JSON Framework

 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 method is this

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];

With your non-error JSON payload you have a top level Array (noted by the beginning [ ), whilst with your error JSON payload you don't.

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

The error code is a nested dictionary object, therefore you would use the following to parse it:

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

NSString *errorCode = [NSString stringWithFormat:@"%@",[(NSDictionary*)[json objectForKey:@"error"]objectForKey:@"code"]];
-(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];
}

使用[jsonArray objectForKey:@"error"]代替valueForKey

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM