Lena Bru
Lena Bru

Reputation: 13937

Using RestKit to map my objects

I use JSON all the time in my apps

in my Android apps, i use Gson to deserialise JSON Objects that come from the server.

What i love about Gson, is that all i need to do is create an POJO class with the given attributes and they are mapped automatically with Gson.fromJSON(JsonString, POJO.class);

and if i want the objects to be named differently than what they arrive from the server, i just add an annotation @SerializedName("server'sName")`

Is there such a way to do that in RestKit? it seems very tedious to name all the properties by hand ? what if i add/remove/rename properties ?

currently this is my class

@interface Test 
@property (nonatomic,assign) int prop1;
@property (nonatomic, assign) NSString *prop2;
@end

this is my JSON :

{ "prop1":10, "prop2":"test"}

this my mapping

   //map class component
    RKObjectMapping *statsMapping = [RKObjectMapping mappingForClass:[Test class]];
    [statsMapping   addAttributeMappingsFromDictionary:@{@"prop1":@"prop1",@"prop2":@"prop2"}];

    // Register our mappings with the provider using a response descriptor
    RKResponseDescriptor *responseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:responseMapping
                                                                                            method:RKRequestMethodGET
                                                                                       pathPattern:nil
                                                                                           keyPath:nil
                                                                                       statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)];
    [objectManager addResponseDescriptor:responseDescriptor];

what i would like is for RestKit to map to my properties (if they exist in both the JSON, and my class) without naming them by name

Upvotes: 3

Views: 588

Answers (1)

Wain
Wain

Reputation: 119021

You can trim your mapping definition with:

[statsMapping addAttributeMappingsFromArray:@[ @"prop1", @"prop2" ]];

RestKit uses the mapping definitions to limit what is being processed and to allow the application of structure and flexibility into the mapping process.

It's possible that you could use RKDynamicMapping and setObjectMappingForRepresentationBlock: to analyse the incoming data in association with a known target class and use reflection to check that the destination variables exist...

Upvotes: 1

Related Questions