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!
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"]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With