【发布时间】:2010-01-27 13:37:31
【问题描述】:
在我的项目中,我使用 TouchJSON 反序列化 JSON 字符串。结果是一个漂亮的 NSDictionary。我想将此字典中的数据放入我的域对象/数据对象中。
有什么好办法吗?一些最佳做法?
也许最好保留 NSDictionary 并跳过域对象?
【问题讨论】:
在我的项目中,我使用 TouchJSON 反序列化 JSON 字符串。结果是一个漂亮的 NSDictionary。我想将此字典中的数据放入我的域对象/数据对象中。
有什么好办法吗?一些最佳做法?
也许最好保留 NSDictionary 并跳过域对象?
【问题讨论】:
这里有两种方法。将-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: 方法非常相似。
【讨论】:
没有内置机制可以做到这一点......我创建了一个使用 KVC 隐喻的小实用程序,将字典属性映射到域对象......乏味且只有 1 个域级别深度。
我还没有尝试过,但 Google Mantle 看起来可以解决问题:
它将 JSON 映射到您的域模型和从您的域模型映射。
【讨论】: