Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing NSString as JSON

I have read several forums but am seemingly unable to accomplish this simple task. I have a View in Xcode that points to a PHP script and stores the results as the NSString below:

[{"id":"16","name":"Bob","age":"37"}]

I am having trouble parsing this NSString. This is how I am getting the contents of the NSString:

NSString *strURL = [NSString stringWithFormat:@"http://www.website.com/json.php?
id=%@",userId];

// to execute php code
NSData *dataURL = [NSData dataWithContentsOfURL:[NSURL URLWithString:strURL]];

// to receive the returend value
NSString *strResult = [[NSString alloc] initWithData:dataURL 
encoding:NSUTF8StringEncoding];

How do I convert the result (strResult) to JSON and take the objects out of it? I would assume its something like below, but I know I am missing something

NSString *name = [objectForKey:@"name"];
NSString *age = [objectForKey:@"age"];

Any help would be great. Thank you!

like image 771
Brandon Avatar asked Jan 30 '26 16:01

Brandon


1 Answers

use the class NSJSONSerialization to read it

id jsonData = [string dataUsingEncoding:NSUTF8StringEncoding]; //if input is NSString
id readJsonDictOrArrayDependingOnJson = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:nil];

in your case

NSArray *readJsonArray = [NSJSONSerialization JSONObjectWithData:dataURL options:0 error:nil];
NSDictionary *element1 = readJsonArray[0]; //old style: [readJsonArray objectAtIndex:0]
NSString *name = element1[@"name"]; //old style [element1 objectForKey:@"name"]
NSString *age = element1[@"age"]; //old style [element1 objectForKey:@"age"]
like image 90
Daij-Djan Avatar answered Feb 02 '26 05:02

Daij-Djan