0

我尝试将响应 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

问题是:我不知道如何设置resourceof的映射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 中的资源数组?
---Updated-----
我更新了代码,就是

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

我还用 keypath 更新了响应脚本:

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的属性变成了地图源对象的值。我如何设置配置来解析这种对象?

4

1 回答 1

1

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

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

于 2014-05-13T19:16:02.043 回答