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"
}]
}]
}
Where do I copy that file to in my XCode path?
How do I get this file programmatically?
After I have this file - How do I read the name
value for each colors
object?
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?
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!
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.
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];
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With