如何使用NSJSONSerialization [英] How to use NSJSONSerialization
问题描述
我有一个JSON字符串(来自PHP的 json_encode()
,如下所示:
I have a JSON string (from PHP's json_encode()
that looks like this:
[{"id": "1", "name":"Aaa"}, {"id": "2", "name":"Bbb"}]
我想将此解析为我的iPhone应用程序的某种数据结构。我想对我来说最好的事情就是拥有一个字典数组,因此数组中的第0个元素是一个字典,其键为id=>1
和name=> ;Aaa
。
I want to parse this into some sort of data structure for my iPhone app. I guess the best thing for me would be to have an array of dictionaries, so the 0th element in the array is a dictionary with keys "id" => "1"
and "name" => "Aaa"
.
我不明白 NSJSONSerialization
如何存储数据到目前为止,这是我的代码:
I do not understand how the NSJSONSerialization
stores the data though. Here is my code so far:
NSError *e = nil;
NSDictionary *JSON = [NSJSONSerialization
JSONObjectWithData: data
options: NSJSONReadingMutableContainers
error: &e];
这只是我在另一个网站上看到的一个例子。我一直试图通过打印出eleme的数量来读取 JSON
对象nts和类似的东西,但我总是得到 EXC_BAD_ACCESS
。
This is just something I saw as an example on another website. I have been trying to get a read on the JSON
object by printing out the number of elements and things like that, but I am always getting EXC_BAD_ACCESS
.
我如何使用 NSJSONSerialization
解析上面的JSON,并将其转换为我提到的数据结构?
How do I use NSJSONSerialization
to parse the JSON above, and turn it into the data structure I mentioned?
推荐答案
你的根json对象不是字典而是数组:
Your root json object is not a dictionary but an array:
[{"id": "1", "name":"Aaa"}, {"id": "2", "name":"Bbb"}]
这可能会让你清楚地了解如何处理它:
This might give you a clear picture of how to handle it:
NSError *e = nil;
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData: data options: NSJSONReadingMutableContainers error: &e];
if (!jsonArray) {
NSLog(@"Error parsing JSON: %@", e);
} else {
for(NSDictionary *item in jsonArray) {
NSLog(@"Item: %@", item);
}
}
这篇关于如何使用NSJSONSerialization的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!