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
in your case
If you are targeting for iOS 5 and higher just use NSJSONSerialization
http://developer.apple.com/library/ios/#documentation/Foundation/Reference/NSJSONSerialization_Class/Reference/Reference.html
If you are targeting lower than iOS 5, use a JSON parser like this one: http://stig.github.com/json-framework/
And just call JSONValue (or equivalent) method on your JSON string:
By the way, your JSON string looks like an array, and you can not use
objectForKey
to get objects from anNSArray
. You have two options, modify your JSON string response as a dictionary or useobjectAtIndex
to get objects.Try this....