【问题标题】:RestKit: Map nested Array to ObjectRestKit:将嵌套数组映射到对象
【发布时间】:2013-11-26 14:37:34
【问题描述】:

我有两个类来映射 JSON 响应:ItemFrequentProps

项目具有以下属性:

frequentProps, identifier, name

FrequentProps 有属性

propOne
propTwo
propThree
propFour

您可以看到Item 中的frequentPropsFrequentProps 类型。

考虑以下 JSON 响应:

[
    {
        "frequentProps": [
            {
                "propOne": 174
            },
            {
                "propTwo": 9.726
            },
            {
                "propThree": 2.021
            },
            {
                "propFour": 25.07
            }
        ],
        "identifier": "4223",
        "name": "TheName"
    }
]

JSON 的外部部分应该映射到 Item 类的对象,嵌套数组应该映射到 frequentProps,作为对象的属性。不幸的是,frequentProps 没有映射到同名的Items 属性,而是映射到NSArray(如果我将属性的类型定义为NSArray,否则该属性仍然为零)。

这是配置:

RKObjectMapping *itemMapping = [RKObjectMapping mappingForClass:[Item class]];
[item addAttributeMappingsFromDictionary:[Item attributesMapping]];
RKObjectMapping *frequentPropsMapping = [RKObjectMapping mappingForClass:[FrequentProps class]];    
[frequentPropsMapping addAttributeMappingsFromDictionary:[FrequentProps attributesMapping]];
[itemMapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:@"frequentProps"
                                                                                      toKeyPath:@"frequentProps"
                                                                                    withMapping:frequentProps]];

// adding the response descriptor, etc...

如何将frequentProps 直接映射到FrequentProps 类型的对象,该对象仍然是Item 的属性?

【问题讨论】:

    标签: ios restkit restkit-0.20


    【解决方案1】:

    您不能,因为在映射中无法指定您正在对数组进行索引并将该索引放入指定的键中。我希望这永远不会得到支持。

    不理想,但是:您还可以使用自定义 setter 方法添加数组属性。调用 setter 时,通过创建 FrequentProps 的实例并根据数组内容设置属性来改变数据。

    【讨论】:

    • 我担心会是这样。感谢您的建议,如果 RestKit 中没有指定的用例,我会想到这样的事情。
    猜你喜欢
    • 1970-01-01
    • 2013-08-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多