2

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?

Andreas Aarsland
  • 945
  • 2
  • 11
  • 27

2 Answers2

1

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
  • 286,113
  • 34
  • 456
  • 610
  • I think the initWithAttributes will do, but a mapping framework would be sweeter... Thanks! – Andreas Aarsland Jan 28 '10 at 13:01
  • @Andi: True, but sometimes, a framework is overkill when you just need something lightweight and quick to cover the basics. Thanks, Rob! Using the objectForKey: method in an initializer is a great way to go! – Old McStopher Mar 17 '12 at 19:02
0

There is no built-in mechanism to do this ... and I have created a small utility that uses a KVC metaphor, to map dictionary attributes to a domain object .. tedious and only 1 domain level deep.

I have not tried this yet, but Google Mantle looks like it might do the trick:

Google Mantle

It maps JSON to and from your domain model.

pkasson
  • 37
  • 5