Haspemulator
Haspemulator

Reputation: 11308

RestKit 0.2: flattening the hierarchy in JSON

Maybe there's a similar question here, but I could not find it. So I have the RestKit 0.2pre4 and want to map such JSON ...

{
    "location": {
        "position": {
            "latitude": 53.9675028,
            "longitude": 10.1795594
        }
    },
    "id": "da3224f2-5919-42f2-9dd8-9171088f4ad7",
    "name": "Something even more beautiful",
}

... to such an object:

@interface FavoritePlace : NSManagedObject

@property (nonatomic, retain) NSString * name;
@property (nonatomic, retain) NSString * placeId;
@property (assign, nonatomic) double latitude;
@property (assign, nonatomic) double longitude;

@end

As you can see, the point is that I don't want to create a relationship and store "Location" object in database separately - it just doesn't make sense. Therefore I want to assign those nested things (location.position.latitude and location.position.longitude) to particular properties of object itself. How to achieve that?

Upvotes: 1

Views: 273

Answers (2)

Haspemulator
Haspemulator

Reputation: 11308

Apparently, I did a wild ass guess and it worked! Here's the mapping which does the trick:

[placeMapping addAttributeMappingsFromDictionary:@{
     @"id": @"placeId",
     @"name": @"name",
     @"location.position.latitude": @"latitude",
     @"location.position.longitude": @"longitude"     
     }];

Have not found this in documentation, but maybe it's just me... Anyway, if something logical, but undocumented, works, then framework should be good. :) RestKit FTW!

Upvotes: 1

Francisco Hernandez
Francisco Hernandez

Reputation: 2468

You can pass the string containig the json string to nsdata with

NSData* jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];

Then, you will be able to parse de json data with the iOS API with

NSError *error;
NSDictionary *json = jsonData ? [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error] : nil;

Now, examine the generated NSDictionary (with NSlog for example), fill your 'FavoritePlace' object and persist it.

Hope helps!

Upvotes: 0

Related Questions