反序列化 JSON 后将 NSDictionary 映射到域对象

发布于 2024-08-19 07:39:43 字数 157 浏览 4 评论 0原文

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

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

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

In my project I use TouchJSON to deserialize a JSON string. The result is a pretty NSDictionary. I would like to get the data in this dictionary into my domain objects / data objects.

Is there a good way to do this? Some best practices?

Perhaps the best to keep the NSDictionary and skip the domain objects?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

方觉久 2024-08-26 07:39:43

这里有两种方法。向您的数据对象添加一个 -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: 方法将非常相似。

There are two approaches here. Either add an -initWithJSONString: method to your data objects and pass the JSON directly to them for break-down, or add an -initWithAttributes: method that takes a dictionary that you get from parsing the JSON. For example:

- (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;
}

Creating an -initWithJSONString: method would be very similar.

街道布景 2024-08-26 07:39:43

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

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

Google Mantle

它映射 JSON往返于您的域模型。

There is no built-in mechanism to do this ... and I have created a small utility that uses a KVC metaphor, to map dictionary attributes to a domain object .. tedious and only 1 domain level deep.

I have not tried this yet, but Google Mantle looks like it might do the trick:

Google Mantle

It maps JSON to and from your domain model.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文