解析本地文件中的JSON内容

时间:2011-08-15 11:03:29

标签: objective-c json

如何解析存储在应用程序中的JSON文件?

这些是我的JSON文件内容:

[{"number":"01001","lieu":"paris"}{"number":"01002","lieu":"Dresden"}]

我尝试过以下代码:

NSString *filePath = [[NSBundle mainBundle] pathForResource:@"file" ofType:@"json"];

//création d'un string avec le contenu du JSON
NSString *myJSON = [[NSString alloc] initWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:NULL];   

//Parsage du JSON à l'aide du framework importé
NSDictionary *json    = [myJSON JSONValue];

NSArray *statuses    =  [json objectForKey:@"number"];

for (NSDictionary *status in statuses)
{
    NSLog(@"%@ ", [status objectForKey:@"lieu"]);
}

2 个答案:

答案 0 :(得分:25)

首先,请注意JSON字符串中的两个对象之间缺少逗号。

其次,请注意您的JSON字符串包含顶级数组。所以,而不是:

NSDictionary *json = [myJSON JSONValue];

使用:

NSArray *statuses = [myJSON JSONValue];

数组中的每个元素都是一个对象(字典),它有两个名称 - 值对(键 - 对),一个用于number,另一个用于lieu

for (NSDictionary *status in statuses) {
    NSString *number = [status objectForKey:@"number"];
    NSString *lieu = [status objectForKey:@"lieu"];

    …
}

您可能还想检查是否可以读取该文件:

//Creating a string with the contents of JSON
NSString *myJSON = [[NSString alloc] initWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:NULL];
if (!myJSON) {
    NSLog(@"File couldn't be read!");
    return;
}

答案 1 :(得分:2)

以下是建议的完整实施:

NSString *jsonFilePath = [[NSBundle mainBundle] pathForResource:@"file" ofType:@"json"];
if (!jsonFilePath) {
    // ... do something ...
}

NSError *error = nil;
NSInputStream *inputStream = [[NSInputStream alloc] initWithFileAtPath:jsonFilePath];
[inputStream open];
id jsonObject = [NSJSONSerialization JSONObjectWithStream: inputStream
                                                        options:kNilOptions
                                                          error:&error];
[inputStream close];
if (error) {
    // ... do something ...
}
相关问题