我正在编写一个 Objective C/iOS 模块,使用 Stig Brautaset 的 JSON 库将文本文件解析为 JSON 字典。
有没有一种简单的方法可以将单个 JSON 文件解析为字典对象数组,或者我是否必须创建一个字典对象并从中提取不同的对象?
作为背景,我当前使用多个文件,每个对象一个。我的 JSON 文件看起来像这样:
{
"colorname": "red",
"foos": [
{
"type": "cherry",
"category": "fruit"
},
{
"type": "redvines",
"category": "bar"
}
]
}
{
"colorname": "green",
"foos": [...]
}
{
"colorname": "blue",
"foos": [...]
}
等等
我的解析函数是这样的:
NSMutableArray *fooColors = [[[NSMutableArray alloc] init] autorelease]
for (NSString *thisFile in fileList) {
NSString *entireFile = [NSString stringWithContentsOfFile:thisFile
encoding:NSUTF8StringEncoding
error:nil];
NSDictionary *fooList = (NSDictionary*)[entireFile JSONValue];
[fooColors addObject:dataObject];
}
但我宁愿将所有 JSON 对象放在一个文件中。我会在像这样的一个顶级字典中完成这一切吗?
{
"colors": [
{
"colorname": "red",
"foos": [
{
"type": "cherry",
"category": "fruit"
},
{...}
]
},
{"colorname": "green",
"foos":[...]
},
{"colorname": "blue",
"foos":[...]
},
*etc.*
]
}
是否有更简单的方法来省去 JSON 文本的前两行和最后两行并将其作为字典对象数组读取?如果是这样,解析函数会是什么样子?
如果这是一个新手问题,请提前道歉。
最佳答案
JSON 中最外层的对象可以是数组。它不一定是记录/字典。 SBJSON 将返回一个 NSArray 给您。
[
{
"colorname": "red",
"foos": [
{
"type": "cherry",
"category": "fruit"
},
{...}
]
},
{"colorname": "green",
"foos":[...]
},
{"colorname": "blue",
"foos":[...]
},
*etc.*
]
关于iphone - 数组可以是顶级 JSON 对象吗? (在 Objective C,Stig Brautaset 的库中),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9952964/