如何使用 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" =>啊"
.
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];
这只是我在另一个网站上看到的一个例子.我一直试图通过打印出元素的数量和类似的东西来读取 JSON
对象,但我总是得到 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屋!