0

I'm new to ios development. Now I get a JSON file from server.

I use NSDictionary to get objects. When I debug, I could get "name", "address" values.

But I don't know how can I get all "dish" elements from "recommendation" Object? In java development, I know recommendation is an object, and "dish" is an array element. But I don't know what happen in ios.

{
      "results": [
        {
          "name": "ollise",
          "address": "columbia university",
          "geo": [
            {
              "coordinates": 40
            },
            {
              "coordinates": 70
            }
          ],
          "logo": "http:\/\/a0.twimg.com\/profile_images\/3159758591\/1548f0b16181c0ea890c71b3a55653f7_normal.jpeg",
          "recommendation": [
            {
              "dish": "dish1"
            },
            {
              "dish": "dish2"
            }
          ],

        }
      ]
    }

By the way, in JSON, I store URL of an image in "logo", but I cannot get the value when debugging. Should I use some special format?

[Restaurant setname:[Dict objectForKey:@"name"]] // I could get name
[Restaurant setlogo:[Dict objectForKey:@"logo"]]   // I can get nothing!
Freya Ren
  • 2,086
  • 6
  • 29
  • 39
  • Check my method [here](http://stackoverflow.com/questions/14958883/ios-serialize-deserialize-complex-json-generically-from-nsobject-class). It is clean, generic and less error-prone – Alphapico May 28 '13 at 10:06

1 Answers1

2

This is the way to do it

NSDictionary *response = [NSJSONSerialization JSONObjectWithData:yourData options:NSJSONReadingMutableLeaves error:nil];
NSDictionary *results = [[response objectForKey:@"results"] objectAtIndex:0];
NSString *name = [response objectForKey:@"name"];
//... get other objects
NSArray *recommendation = [results objectForKey:@"recommendation"];
NSDictionary *recommendation1 = [recommendation objectAtIndex:0];
NSDictionary *recommendation2 = [recommendation objectAtIndex:1];
NSString *dish = [recommendation1 objectForKey@"dish"];
NSString *dish1 = [recommendation2 objectForKey@"dish"];
[Restaurant setname:name];
NSString *logo = [results objectForKey:@"logo"];
[Restaurant setlogo:logo];

The results is the same dictionary as the one in the JSON. Treat anything with braces ({}) as an NSDictionary and brackets ([]) as an NSArray. dish is not an array element, it is a key in a dictionary that is an array element.

Chris Loonam
  • 5,735
  • 6
  • 41
  • 63