Reading a JSON file in Objective-C

I searched for about two hours, and it seems that someone has no clear explanation of how to read the JSON file in Objective-C .

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

 { "colors": [{ "name": "green", "pictures": [{ "pic": "pic1.png", "name": "green1" }, { "pic": "pic2.png", "name": "green2" }] }, { "name": "yellow", "pictures": [{ "pic": "pic3.png", "name": "yellow1" }] }] } 
  • Where can I copy this file to my Xcode path?

  • How can I get this file programmatically?

  • After this file - How do I find out the name value for each colors object?

  • How would I say "for each image in a color named green , get the name value in NSString"?

I tried several methods, but have not yet come to a conclusion. Am I just misunderstanding the concept of JSON?

+6
source share
1 answer

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

Be sure to check the box next to โ€œCopy items if necessaryโ€ and add it for the right purpose.

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]; } 
+16
source

Source: https://habr.com/ru/post/1013295/


All Articles