将NSString解析为JSON [英] Parsing NSString as JSON
问题描述
我已经阅读了多个论坛,但似乎无法完成此简单任务.我在Xcode中有一个指向PHP脚本的视图,并将结果存储为以下NSString:
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"}]
[{"id":"16","name":"Bob","age":"37"}]
我在解析此NSString时遇到麻烦.这就是我获取NSString内容的方式:
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];
如何将结果(strResult)转换为JSON并从中取出对象?我会假设其如下所示,但我知道我缺少了一些东西
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!
推荐答案
使用类NSJSONSerialization读取它
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"]
这篇关于将NSString解析为JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!