使用 RestKit 在 NSDictionary 中嵌套对象 [英] Nested objects in NSDictionary with RestKit

查看:57
本文介绍了使用 RestKit 在 NSDictionary 中嵌套对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 JSON 文档,其中包含具有未知键的对象中具有已知架构的对象,我想用 RestKit 映射它.让我解释一下:

<预><代码>{目的":{"unknownKey1" : {"data1" : "...", "data2" : "..."},"unknownKey2" : {"data1" : "...", "data2" : "..."},unknownKey3":{data1":...",data2":..."}}}

键为object"的对象的设置只有在运行时才知道.对象中包含的键具有随机名称.但是,我知道存储在这些未知键中的对象的确切架构.

现在我想将带有键object"的对象内容映射到 NSDictionary,因为它提供了对随机键的轻松访问.但是,由于存储在这些键中的对象的架构是已知的,我希望将它们映射到自定义对象.

那么是否有可能映射到包含这些对象的 NSDictionary?我还没有找到解决方案...

解决方案

你可以这样做:

RKObjectMapping* mapping = [RKDynamicObjectMapping dynamicMapping];mapping.objectMappingForDataBlock = ^(id 数据) {NSDictionary* object = [data objectForKey: @"object"];NSArray* keys = [object allKeys];RKObjectMapping* dataMapping = [RKObjectMapping objectMapping];//使用key定义映射返回数据映射;};

I have a JSON document which contains objects with known schema in an object with unknown keys and I'll like to map that with RestKit. Let me explain this:

{
    "object":
    {
        "unknownKey1" : {"data1" : "...", "data2" : "..."},
        "unknownKey2" : {"data1" : "...", "data2" : "..."},
        "unknownKey3" : {"data1" : "...", "data2" : "..."}
    }
}

The setup of the object with key "object" is only known at runtime. The keys included in the object have random names. However, I know the exact schema of the objects stored at these unknown keys.

Now I would like to map the content of the object with key "object" to a NSDictionary as it provides easy access to the random keys. However, as the schema of the objects stored at these keys is known, I would like them to be mapped to custom objects.

So is there a possibility to map to a NSDictionary containing these objects? I haven't found a solution...

解决方案

You could do something like this:

RKObjectMapping* mapping = [RKDynamicObjectMapping dynamicMapping];
mapping.objectMappingForDataBlock = ^(id data) {
    NSDictionary* object = [data objectForKey: @"object"];
    NSArray* keys = [object allKeys];

    RKObjectMapping* dataMapping = [RKObjectMapping objectMapping];
    //Use the keys to define mapping
    return dataMapping;
};

这篇关于使用 RestKit 在 NSDictionary 中嵌套对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆