2014-01-13 161 views
3

我使用JSON在我的应用程序使用RestKit映射我的对象

在我的Android应用程序,我使用GSON到deserialise是来自服务器的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

您可以修剪你的映射定义:

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

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

这有可能是你可以使用RKDynamicMappingsetObjectMappingForRepresentationBlock:来分析联想输入数据与已知目标类和使用反射来检查目标存在变数......

+0

做我需要做的反射,或RestKit做到了吗? –

+0

RestKit反映了变量的数据类型,以确定在映射过程中需要什么样的翻译,但它并没有反映出存在哪些变量来知道要映射哪些变量 - 它需要告知哪些键名映射。 – Wain

+0

为什么没有RestKit创建一个“默认”映射方案,它依赖于要映射的变量的名称,并且如果某些变量丢失,它们将保留为零或丢弃,具体取决于它们的位置(JSONvsClass)? –