0

如何映射相同类型的嵌套对象?我有一个 xml,其中的对象可能包含多个相同类型的对象:

<entry location="l1">
    <entry location="l1.1">
        <entry location="l1.1.1">
        </entry>
        <entry location="l1.1.2">
        </entry>
    </entry>
</entry>

如果我添加具有相同映射的属性映射,我会得到无限递归:

+ (RKObjectMapping *)objectMapping {
    RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[Entry class]];
    [mapping addAttributeMappingsFromDictionary:@{@"location": @"location"}];
    [mapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:@"nextEntries"
                                                                            toKeyPath:@"entries"
                                                                          withMapping:[Entry objectMapping]]];

    return mapping;
}

是否可以将子对象添加到每个父对象的数组中?

干杯

//编辑:以下代码对我有用:

+ (RKObjectMapping *)objectMapping
{
    RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[Entry class]];
    [mapping addAttributeMappingsFromDictionary:@{@"location": @"location"}];

    RKObjectMapping *innerMapping = [RKObjectMapping mappingForClass:[Entry class]];
    [innerMapping addAttributeMappingsFromDictionary:@{@"location": @"location"}];

    [mapping addPropertyMapping:[RKRelationshipMapping
        relationshipMappingFromKeyPath:@"entry"
        toKeyPath:@"entries"
        withMapping:innerMapping]];

    return mapping;
}
4

1 回答 1

2

我还没有尝试过,所以我不知道它是否会起作用,但试试这个:

+ (RKObjectMapping *)objectMapping
{
    RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[Entry class]];
    [mapping addAttributeMappingsFromDictionary:@{@"location": @"location"}];

    RKObjectMapping *innerMapping = [RKObjectMapping mappingForClass:[Entry class]];
    [innerMapping addAttributeMappingsFromDictionary:@{@"location": @"location"}];

    [mapping addPropertyMapping:[RKRelationshipMapping
        relationshipMappingFromKeyPath:@"nextEntries"
        toKeyPath:@"entries"
        withMapping:innerMapping]];

    return mapping;
}

不确定这toKeyPath:@"entries"是否正确,它可能需要toKeyPath:@"entry"基于您的 XML。

无限递归是因为您从自身([Entry objectMapping])调用相同的方法,它与映射本身无关。

于 2013-05-29T11:36:22.140 回答