How should I read the data from a json string? iphone How should I read the data from a json string? iphone json json

How should I read the data from a json string? iphone


Your JSON is invalid. Fix it. This site is your friend.

http://jsonlint.com/


You need to code more defensively and you need to report errors as they are found.

Firstly check if the JSON parsing failed and if so report the error:

 NSData *data1 = [jsonResponse1 dataUsingEncoding:NSUTF8StringEncoding];jsonArray = [NSJSONSerialization JSONObjectWithData:data1 options:kNilOptions error:&err];if (jsonArray == nil){    NSLog(@"Failed to parse JSON: %@", [err localizedDescription]);    return;}

Secondly if those keys are not in the JSON, objectForKey: will return nil and when you attempt to add that to the arrays, it will throw an exception, which is something you want to avoid:

for (NSDictionary *json in jsonArray) {    NSString * value = [json objectForKey:@"van"];    if (value != nil)    {        [self.van addObject:value];        lbl1.text = value;    }    else    {         NSLog(@"No 'van' key in JSON");    }    NSString * value1 = [json objectForKey:@"vuan"];    if (value1 != nil)    {        [self.vuan addObject:value1];        lbl4.text = value1;    }    else    {        NSLog(@"No 'vuan' key in JSON");    }}

So in summary: runtime errors will occur so you need to ensure you handle them. When they occur you need to report them with as much information possible so that you can diagnose and fix them.