Parsing NSString as JSON

2019-05-29 03:44发布

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!

3条回答
贪生不怕死
2楼-- · 2019-05-29 04:08

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"]
查看更多
Ridiculous、
3楼-- · 2019-05-29 04:11

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:

NSDictionary *dict= [strResult JSONValue];

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

By the way, your JSON string looks like an array, and you can not use objectForKey to get objects from an NSArray. You have two options, modify your JSON string response as a dictionary or use objectAtIndex to get objects.

查看更多
ゆ 、 Hurt°
4楼-- · 2019-05-29 04:16

Try this....

NSString * strResult = [[NSString alloc] initWithData:responseMutableData encoding:NSUTF8StringEncoding];  
SBJSON *jsonParser = [[SBJSON alloc]init];
if([[jsonParser objectWithString:strResult] isKindOfClass:[NSArray class]])
{
    NSArray *jsonArr=[jsonParser objectWithString: strResult];
    NSDictionary *firstDictonary = [jsonArr objectAtIndex:0];
    NSString *name = [firstDictonary valueForKey:@"name"];
    NSString *age = [firstDictonary valueForKey:@"age"];
}
查看更多
登录 后发表回答