32

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?

Vemonus
  • 868
  • 1
  • 16
  • 28
TomQDRS
  • 875
  • 1
  • 7
  • 20
  • 2
    well, to be honest, you must be searching wrong. Instead of searching for all in one, search the following way: 1. How to add file to my Xcode project? 2. How to read file programatically using objective c? 3. How to unarchive JSON file objective C? – dirtydanee Dec 19 '16 at 16:04
  • Do you really think I would have asked a question here if I hadn't done that already? – TomQDRS Dec 19 '16 at 16:04
  • 2
    1: http://stackoverflow.com/questions/27642521/how-can-i-include-a-txt-file-in-an-xcode-project 2: http://stackoverflow.com/questions/27206176/where-to-place-a-txt-file-and-read-from-it-in-a-ios-project 3&4: It's all about parsing JSON, and there is plenty of questions about it, look for `NSJSONSerialization`. – Larme Dec 19 '16 at 16:13
  • @Larme this question is not that bad, this is literally the only Google search hit on Stack Overflow (and also the #1 search hit) that comes up when I search for "parse JSON file objective-c". If I go digging on SO by searching `[ios] [objective-c] [json] parse` the results are IMO less clear than this one, and with worse answers. If you have a canonical link paste it, otherwise it seems that Google thinks *this is the canonical*. Personally I already knew 1 and 2, if we edit that out of this question, this question is pretty good for (3) – jrh Nov 26 '21 at 14:55
  • @jrh: This is an old question, I'm not the one that marked it as a not enough focused. On SO, we should focus on one question at a time, here there are 4. Well, I guess more three: File + Parsing + Filtering. – Larme Nov 26 '21 at 15:04
  • @Larme sure, but you said "plenty of questions about it" -- can you link one? I'll flag this as a dupe if there's a better question, I agree that it's not great to ask 4 questions at once, but I also don't think it's a huge deal in this specific case, the other 2 were really easily answered in like 1 sentence each, and the last one is IMO a pretty mild extension of (3). As far as I can tell this is the best objc JSON parsing question on Stack Overflow, right now anyway. – jrh Nov 26 '21 at 15:09
  • 1
    @Larme When I wrote this question I was just starting out with actual app development and was thrown into the cold water regarding both the iOS system and, regrettably, Objective C. I realize this question could be seen as "too broad", but the questions it poses are to me connected logically, as in they're all steps of one process I was entirely unclear about. At the time there either weren't singular questions asked about those steps, or I didn't know how to look for them. I would greatly appreciate if this question no longer said closed, because its answer is great and it's popular too. – TomQDRS Nov 27 '21 at 15:15
  • @TomQDRS just to be clear, Larme said that they did not close it. You can see who closed it in the [timeline](https://stackoverflow.com/posts/41226442/timeline), but it's quite hard to contact them. The best we can hope for is somebody voting to reopen (I don't have enough rep for that), or maybe somebody could make a meta topic. I think this question could maybe be helped by editing it so that it's just parsing JSON in objC. In March of 2018 a reopen vote was started but it was unanimously denied, unfortunately. – jrh Nov 27 '21 at 20:45

1 Answers1

61

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

// The return value is either NSArray * or NSDictionary *
- (id)JSONFromFile
{
    NSString *path = [[NSBundle mainBundle] pathForResource:@"colors" ofType:@"json"];
    NSData *data = [NSData dataWithContentsOfFile:path];
    return [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
}
Borzh
  • 5,069
  • 2
  • 48
  • 64
Simon
  • 1,354
  • 1
  • 14
  • 18