views:

191

answers:

1

In my project I use TouchJSON to deserialize a JSON string. The result is a pretty NSDictionary. I would like to get the data in this dictionary into my domain objects / data objects.

Is there a good way to do this? Some best practices?

Perhaps the best to keep the NSDictionary and skip the domain objects?

A: 

There are two approaches here. Either add an -initWithJSONString: method to your data objects and pass the JSON directly to them for break-down, or add an -initWithAttributes: method that takes a dictionary that you get from parsing the JSON. For example:

- (id)initWithAttributes:(NSDictionary *)dict
{
    // This is the complicated form, where you have your own designated
    // initializer with a mandatory parameter, just to show the hardest problem.
    // Our designated initializer in this example is "initWithIdentifier"

    NSString *identifier = [dict objectForKey:MYIdentifierKey];
    self = [self initWithIdentifier:identifier];
    if (self != nil)
    {
        self.name = [dict objectForKey:MYNameKey];
        self.title = [dict objectForKey:MYTitleKey];
    }
    return self;
}

Creating an -initWithJSONString: method would be very similar.

Rob Napier
I think the initWithAttributes will do, but a mapping framework would be sweeter... Thanks!
Andi