Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read JSON file in Objective C [closed]

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.

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. Where do I copy that file to in my XCode path?

  2. How do I get this file programmatically?

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

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

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

like image 870
TomQDRS Avatar asked Dec 19 '16 15:12

TomQDRS


People also ask

How do I read a JSON file in Objective C?

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. Thank you!

How to read JSON file in iOS?

if let path = Bundle. main. path(forResource: "assets/test", ofType: "json") { do { let data = try Data(contentsOf: URL(fileURLWithPath: path), options: . alwaysMapped) let jsonObj = try JSON(data: data) print("jsonData:\(jsonObj)") } catch let error { print("parse error: \(error.


1 Answers

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.

Then do something like this:

- (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];
}
like image 59
Simon Avatar answered Oct 16 '22 07:10

Simon