【问题标题】:Map NSDictionary to domain objects after deserializing JSON反序列化 JSON 后将 NSDictionary 映射到域对象
【发布时间】:2010-01-27 13:37:31
【问题描述】:

在我的项目中,我使用 TouchJSON 反序列化 JSON 字符串。结果是一个漂亮的 NSDictionary。我想将此字典中的数据放入我的域对象/数据对象中。

有什么好办法吗?一些最佳做法?

也许最好保留 NSDictionary 并跳过域对象?

【问题讨论】:

    标签: iphone touchjson


    【解决方案1】:

    这里有两种方法。将-initWithJSONString: 方法添加到您的数据对象并将JSON 直接传递给它们以进行分解,或者添加一个-initWithAttributes: 方法,该方法采用您从解析JSON 中获得的字典。例如:

    - (id)initWithAttributes:(NSDictionary *)dict
    {
        // This is the complicated form, where you have your own designated
        // initializer with a mandatory parameter, just to show the hardest problem.
        // Our designated initializer in this example is "initWithIdentifier"
    
        NSString *identifier = [dict objectForKey:MYIdentifierKey];
        self = [self initWithIdentifier:identifier];
        if (self != nil)
        {
            self.name = [dict objectForKey:MYNameKey];
            self.title = [dict objectForKey:MYTitleKey];
        }
        return self;
    }
    

    创建-initWithJSONString: 方法非常相似。

    【讨论】:

    • 我认为 initWithAttributes 可以,但映射框架会更好......谢谢!
    • @Andi:没错,但有时,当您只需要轻量级且快速涵盖基础知识的东西时,框架就显得有些矫枉过正了。谢谢,罗伯!在初始化程序中使用 objectForKey: 方法是一个很好的方法!
    【解决方案2】:

    没有内置机制可以做到这一点......我创建了一个使用 KVC 隐喻的小实用程序,将字典属性映射到域对象......乏味且只有 1 个域级别深度。

    我还没有尝试过,但 Google Mantle 看起来可以解决问题:

    Google Mantle

    它将 JSON 映射到您的域模型和从您的域模型映射。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-24
      • 1970-01-01
      • 2011-06-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多