Restkit:使用xml进行对象映射

时间:2014-05-13 15:13:34

标签: ios xml-parsing restkit rkobjectmapping

我尝试将响应xml映射到对象中,xml看起来像:


<list version="1.0">
  <meta>
    <type>resource-list</type>
  </meta>
  <resources start="0" count="168">
    <resource classname="Quote">
      <field name="name">Alpha</field>
      <field name="price">10</field>
    </resource>
    <resource classname="Quote">
      <field name="name">Beta</field>
      <field name="price">9</field>
    </resource>
  </resources>
</list>

我想要的是resources部分。我创建了对象模型:


@interface Field : NSObject
@property (nonatomic, strong) NSString *name;
@property (nonatomic, strong) NSNumber *price;
@end
@interface Resources : NSObject
@property (nonatomic, strong) NSNumber *count;
@property (nonatomic, strong) NSArray *resource;
@end

问题是:我不知道如何设置resource Resources的映射。我曾尝试使用映射:

RKObjectMapping *objMapping = [RKObjectMapping mappingForClass:[Field class]];
[objMapping addAttributeMappingsFromArray:@[@"name",@"price"]];</br>

RKObjectMapping *resourcesMapping = [RKObjectMapping mappingForClass:[Resources class]];
[resourcesMapping addAttributeMappingsFromArray:@[@"count"]];
[resourcesMapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:@"resource" toKeyPath:nil withMapping:objMapping]];

RKResponseDescriptor *descriptor = [RKResponseDescriptor responseDescriptorWithMapping:resourcesMapping method:RKRequestMethodGET pathPattern:@"XXXXXX" keyPath:@"list.resources" statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)];

映射完成后,将创建Resources对象。但是它的数组resource仍然是零。

如何获取xml中的资源数组?
---更新-----
我更新了代码,

RKObjectMapping *objMapping = [RKObjectMapping mappingForClass:[Field class]];
objMapping.forceCollectionMapping = YES;
[objMapping addAttributeMappingsFromDictionary:@{@"name":@"name.text"}];  

我还使用keypath更新了respondscripter:

RKResponseDescriptor *descriptor = [RKResponseDescriptor responseDescriptorWithMapping:objMapping method:RKRequestMethodGET pathPattern:@"XXXXX" keyPath:@"list.resources.resource.field" statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)];  

然后在RKObjectManager的成功块中,映射结果具有字段数组。问题是Field的属性都是nil 我查看看起来的日志:


D restkit.object_mapping:RKMapperOperation.m:229 Asked to map source object (
        {
        name = name;
        text = "alpha";
    },
        {
        name = price;
        text = "98.3";
    }

) with mapping  name.text>"
)>
2014-05-14 23:33:57.681 RestKitTest[5138:3307] D restkit.object_mapping:RKMappingOperation.m:859 Starting mapping operation...
2014-05-14 23:33:57.682 RestKitTest[5138:3307] W restkit.object_mapping:RKMappingOperation.m:338 Destination object  rejected attribute value (
    name,
    price
) for keyPath name.text. Skipping...

似乎xml的属性成为地图源对象的值。我如何设置配置来解析这种对象?

1 个答案:

答案 0 :(得分:1)

如果您想使用Resources包装器对象(您不需要),那么您的响应描述符会深入钻取传入数据,关键路径应该只是list。打开跟踪日志记录将帮助您查看XML的解码方式,以及您应该使用的密钥。我不经常使用XML,并且发现将XML直接映射到密钥非常困难。

另请注意,XML解码通常会将所有找到的内容添加到text个键中,因此您需要使用name(而不是name.text作为键,而不是{{1}}。您将需要一个字典来指定源键路径和目标键。