使用RestKit映射我的对象

时间:2014-01-13 13:05:52

标签: ios json restkit restkit-0.20

我在我的应用中一直使用JSON

在我的Android应用中,我使用Gson反序列化来自服务器的JSON对象。

我喜欢Gson,我需要做的就是创建一个具有给定属性的POJO类,并使用Gson.fromJSON(JsonString, POJO.class);自动映射

如果我希望对象的命名方式与从服务器到达的对象不同,我只需添加一个注释@SerializedName(“server'sName”)`

RestKit中有这样的方法吗? 手动命名所有属性似乎非常繁琐? 如果我添加/删除/重命名属性怎么办?

目前这是我的班级

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

这是我的JSON:

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

这是我的映射

   //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];

我希望RestKit能够映射到我的属性(如果它们同时存在于JSON和我的类中),而不是按名称命名它们

1 个答案:

答案 0 :(得分:1)

您可以使用以下方法修剪映射定义:

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

RestKit使用映射定义来限制正在处理的内容,并允许在映射过程中应用结构和灵活性。

您可以使用RKDynamicMappingsetObjectMappingForRepresentationBlock:分析与已知目标类关联的传入数据,并使用反射来检查目标变量是否存在...

相关问题