在Objective C中读取JSON文件 [英] Read JSON file in Objective C

查看:546
本文介绍了在Objective C中读取JSON文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我现在已经搜索了大约两个小时,似乎没有人明确解释如何在Objective C中读取JSON文件

I've been searching around for about two hours now and it seems nobody has a clear explanation of how to read a JSON file in Objective C.

假设我有一个名为 colors.json 的JSON文件,如下所示:

Let's say I have a JSON file called colors.json, looking like this:

{
    "colors": [{
        "name": "green",
        "pictures": [{
            "pic": "pic1.png",
            "name": "green1"
        }, {
            "pic": "pic2.png",
            "name": "green2"
        }]
    }, {
        "name": "yellow",
        "pictures": [{
            "pic": "pic3.png",
            "name": "yellow1"
        }]
    }]
}




  1. 我在哪里将该文件复制到我的XCode路径?

  1. Where do I copy that file to in my XCode path?

如何获取此文件以编程方式?

How do I get this file programmatically?

获得此文件后 - 如何读取每个<$的名称值c $ c> colors obj等等?

After I have this file - How do I read the name value for each colors object?

我怎么说对于每个颜色的图片,名称绿色,得到NSString中的名称值?

How would I say "for each picture in the color with the name green, get the name value in a NSString"?

我'已经尝试了一些方法,但尚未得出结论。我只是理解JSON的概念错误吗?

I've been trying a few methods but haven't reached a conclusion yet. Am I just understanding the concept of a JSON wrong?

推荐答案

只需将您的JSON文件拖到Xcode中的项目导航器窗格中即可与您的类文件出现在同一位置。

Just drag your JSON file into the project navigator pane in Xcode so it appears in the same place as your class files.

确保选中如果需要复制项目复选框,并将其添加到正确的目标。

Make sure to select the 'Copy items if needed' tick box, and add it to the correct targets.

然后做这样的事情:

- (void)doSomethingWithTheJson
{
    NSDictionary *dict = [self JSONFromFile];

    NSArray *colours = [dict objectForKey:@"colors"];

    for (NSDictionary *colour in colours) {
        NSString *name = [colour objectForKey:@"name"];
        NSLog(@"Colour name: %@", name);

        if ([name isEqualToString:@"green"]) {
            NSArray *pictures = [colour objectForKey:@"pictures"];
            for (NSDictionary *picture in pictures) {
                NSString *pictureName = [picture objectForKey:@"name"];
                NSLog(@"Picture name: %@", pictureName);
            }
        }
    }
}

- (NSDictionary *)JSONFromFile
{
    NSString *path = [[NSBundle mainBundle] pathForResource:@"colors" ofType:@"json"];
    NSData *data = [NSData dataWithContentsOfFile:path];
    return [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
}

这篇关于在Objective C中读取JSON文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆