2

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

有没有好的方法来做到这一点?一些最佳实践?

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

4

2 回答 2

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:方法将非常相似。

于 2010-01-27T14:38:02.687 回答
0

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

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

谷歌斗篷

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

于 2013-05-23T11:12:30.947 回答