Design a data model to contain JSON objects


#1

I’m calling a URL to retrieve an array JSON objects (restaurants). And I’m trying to parse it using my Objective-C Model.

"restaurants" : [
{
    "name": "Burger Bar",
    "backgroundImageURL": "http://somthing.com/Images/1.png",
    "category" : "Burgers",
        "contact": {
            "phone": "1231231231",
            "formattedPhone": "(123) 123-1231",
            "twitter": "1twitter"
        },
        "location": {
            "address": "5100 Belt Line Road, STE 502",
            "crossStreet": "Dallas North Tollway",
            "lat": 32.950787,
            "lng": -96.821118,
            "postalCode": "75254",
            "cc": "US",
            "city": "Addison",
            "state": "TX",
            "country": "United States",
            "formattedAddress": [
                "5100 Belt Line Road, STE 502 (Dallas North Tollway)",
                "Addison, TX 75254",
                "United States"
            ]
        }
},
{
    "name": "seafood Kitchen",
    "backgroundImageURL": "http://somthing.com/Images/2.png",
    "category": "Seafood",
        "contact": {
            "phone": "3213213213",
            "formattedPhone": "(321) 321-3213",
            "twitter": "2twitter"
        },
        "location": {
            "address": "18349 Dallas Pkwy",
            "crossStreet": "at Frankford Rd.",
            "lat": 32.99908456526653,
            "lng": -96.83018780592823,
            "postalCode": "33331",
            "cc": "US",
            "city": "Dallas",
            "state": "TX",
            "country": "United States",
            "formattedAddress": [
                "18349 Dallas Pkwy (at Frankford Rd.)",
                "Dallas, TX 75287",
                "United States"
            ]
        }
}```


Model 

@interface BRTRestaurant : NSObject

@property (nonatomic, strong) NSString *name;
@property (nonatomic, strong) NSString *category;
@property (nonatomic, strong) NSString *backgroundImageURL;
@property (nonatomic, strong) NSDictionary *contact;


@end

Fetching JSON

-(void)fetchJSON {
    NSString *requestString = restaurantURL;
    NSURL *url = [NSURL URLWithString:requestString];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    _sessionTask = [self.session dataTaskWithRequest:request
                                   completionHandler:^(NSData * data, NSURLResponse * response, NSError * error) {
                                       NSDictionary *jsonObject = [NSJSONSerialization JSONObjectWithData:data
                                                                                                  options:0
                                                                                                    error:nil];
                                       
                                       self.restaurants = jsonObject[@"restaurants"];
                                       
                                       
                                       dispatch_async(dispatch_get_main_queue(), ^{
                                           [self.collectionView reloadData];
                                       });
                                   }];
    [self.sessionTask resume];
};

I successfully make the JSON call but how can I  use an instance of BRTRestaurant instead?

#2

The way I typically do this is to move the logic for extracting info from a dictionary to the model itself, so you’d have something like this:

- (instancetype)initWithDictionary(NSDictionary *)dictionary {
   if (self = [super init]) {
        self.name = dictionary[@"name"];
        self.category = dictionary[@"category"];
        self.backgroundImageURL = dictionary["backgroundImageURL"];  // I'd be careful about naming here, as this is a string, not an NSURL

        // I'd make contact it's own class that has a similar initializer, so you can do this:
        self.contact = [[BRTContact alloc] initWithDictionary:dictionary[@"contact"]];
   }

   return self;
}

Finally, when you want to build an array of these things:

NSMutableArray* restaurants = [NSMutableArray array];
for (id restaurantDictionary in jsonObject[@"restaurants"]) {
    [restaurants addObject:[[BRTRestaurant alloc] initWithDictionary:restaurantDictionary]];
}
self.restaurants = restaurants;

(Forgive me for any typos, it’s been a minute since I wrote Objective-C! :wink: )

Hope this helps!