解析本地文件中的 JSON 内容

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7064200/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 17:57:23  来源:igfitidea点击:

Parse JSON contents in local file

objective-cjson

提问by cs1.6

How can I parse my JSON file stored in the application?

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

These are in my JSON file contents:

这些在我的 JSON 文件内容中:

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

I've tried the following code:

我试过以下代码:

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"]);
}

回答by

Firstly, note there's a comma missing between the two objects in your JSON string.

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

Secondly, note that your JSON string contains a top-level array. So, instead of:

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

NSDictionary *json = [myJSON JSONValue];

use:

用:

NSArray *statuses = [myJSON JSONValue];

Each element in the array is an object (a dictionary) with two name-value pairs (key-object pairs), one for numberand another one for lieu:

数组中的每个元素都是一个对象(字典),具有两个名称-值对(键-对象对),一个 fornumber和另一个 for lieu

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

    …
}

You might also want to check whether the file could be read:

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

//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;
}

回答by Dirty Henry

Here is a suggested full implementation:

这是建议的完整实现:

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 ...
}