How to read data from json string? iphone

I have in NSString "[{"van" : 1,312, "vuan":12,123}] , and to get these values ​​for each key, I do this:

  NSData *data1 = [jsonResponse1 dataUsingEncoding:NSUTF8StringEncoding]; jsonArray = [NSJSONSerialization JSONObjectWithData:data1 options:kNilOptions error:&err]; self.van = [NSMutableArray arrayWithCapacity:1]; self.vuan = [NSMutableArray arrayWithCapacity:1]; for (NSDictionary *json in jsonArray) { NSString * value = [json objectForKey:@"van"]; [self.van addObject:value]; lbl1.text = value; NSString * value1 = [json objectForKey:@"vuan"]; [self.vuan addObject:value1]; lbl4.text = value1; } 

Maybe I don't need to use an array and convert NSData directly to NSDictionary .

In any case, I do not understand why jsonArray is nil , although jsonResponse1 contains the values ​​that I wrote above.

EDIT: My boss wrote the json string incorrectly. Thank you all for your suggestions! :)

+4
source share
2 answers

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

http://jsonlint.com/

+13
source

You need to code more securely, and you need to report bugs as they are found.

First, check to see if the JSON session has figured out, and if so, report an 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 these keys are not in JSON, objectForKey: will return nil , and when you try to add this to arrays, it will throw an exception, which 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 short: runtime errors will occur, so you need to ensure that they are handled. When they happen, you need to give as much information as possible about them so that you can diagnose and correct them.

+1
source

All Articles