Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 536
Lena Bru Avatar asked Feb 13 '26 21:02

Lena Bru


1 Answers

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...

like image 114
Wain Avatar answered Feb 16 '26 10:02

Wain



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!