Question

I am trying to make an weather app, I found a great JSON weather API online. I am using

NSData * data = [NSData dataWithContentsOfURL: [NSURL URLWithString: absoluteURL]];
NSError * error;
NSDictionary * json = [NSJSONSerialization JSONObjectWithData: data //1
  options: kNilOptions 
  error: & error
];
NSLog(@"%@", json);
NSLog([NSString stringWithFormat: @"location: %@", [json objectForKey: @"status"]]);

to get the data, but it wont work, the log returns (null). Can someone plase explain to me how I can get the strings and values of the JSON file? Thanks!

Was it helpful?

Solution

Edit: Change your code from line 3 (including) to:

NSDictionary * json = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
NSArray *meta = json[@"objects"];

for (NSDictionary *aDict in meta) {
    NSDictionary *location = aDict[@"location"];
    NSLog(@"%@", location);
}

This NSLog()s all the locations in your JSON response.

If you want the city and country only once you can do the following:

NSDictionary *location = json[@"objects"][0][@"location"];
NSString *country = location[@"country"];
NSString *locality = location[@"locality"];

NSLog(@"country: %@", country);
NSLog(@"locality: %@", locality);

Output:

country: Germany
locality: Hauzenberg

OTHER TIPS

There is no element "status" in the root of your JSON. The json object will contain exactly same hierarchy as your JSON. In your case, it'll look like this:

root (dictionary)
  |
  -- "objects": (array)
        |
        -- (dictionary)
              |
              -- "sources" (array) 
              -- "weather" (dictionary)
...

You get the idea.

Try this:

for (NSDictionary *object in json[@"objects"])
{
    NSLog([NSString stringWithFormat: @"location: %@", object[@"weather"][@"status"]]);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top