RestKit - Map keypath of an array to the object in

2019-05-05 13:53发布

问题:

I really stack up parsing this particular response with RestKit 0.20:

"addons": [
    {
        "id": 1,
        "name": "Addon one",
        "version": 2
    },
    {
        "id": 2,
        "name": "Addon two",
        "version": 3
    }
],
"forms": [
    {
        "id": 1,
        "name": "Form one",
        "version": 1
    }
]

The problem is that I need to translate the response to an array of object of the same class, such as

@interface MyCoreDataObject : NSManagedObject

@property (nonatomic, retain) NSString * uid;
@property (nonatomic, retain) NSNumber * version;
@property (nonatomic, retain) NSString * name;
@property (nonatomic, retain) NSString * type;

@end

Given that, the key for the array of object should map to the type property and as the result for the response above the mapped result should be look like an array of objects (and table in the database):

uid     name            version     type
1       Addon one       2           addons
2       Addon two       3           addons
1       Form one        1           forms

This is also important, that ID and Type are used as an identity attribute, so I cannot set the type value after mapping is completed, because in this case the RestKit will not be able to find the object that already in the DB and create another one instead of updating that existing one.

Does it possible to solve that problem?

Thank everyone for the answer!

P.S.: During my struggling I found some ways to do it, like creating an object for particular type (for addon, for form and so on), or set type after the mapping is done, but it seams to be really heavy solutions for that simple problem.

回答1:

I'd have to say that you should create your own JSON serialisation class and register it. You class will deserialise as normal but then check and mutate the result to decompose the type information.


Original answer that ignored the array problem:

You need to use addAttributeMappingFromKeyOfRepresentationToAttribute: which allows you to extract that key and use it as a value.