Swift 4 Codable;如何使用单个根级密钥解码对象 [英] Swift 4 Codable; How to decode object with single root-level key

查看:81
本文介绍了Swift 4 Codable;如何使用单个根级密钥解码对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将Swift 4 Codable协议用于JSON数据.我的数据经过格式化,以使得在根级别只有一个键,并且包含一个包含我所需属性的对象值,例如:

I'm using the Swift 4 Codable protocol with JSON data. My data is formatted such that there is a single key at the root level with an object value containing the properties I need, such as:

{
  "user": {
    "id": 1,
    "username": "jdoe"
  }
}

我有一个User结构可以解码user键:

I have a User struct that can decode the user key:

struct User: Codable {
  let id: Int
  let username: String
}

由于idusernameuser的属性,而不是根目录级别,因此我需要创建一个包装器类型,如下所示:

Since id and username are properties of user, not at the root level, I needed to make a wrapper type like so:

struct UserWrapper: Codable {
  let user: User
}

然后我可以通过UserWrapper解码JSON,并且User也会被解码.似乎有很多冗余代码,因为我需要对每种类型都有一个额外的包装器.有没有办法避免这种包装模式,或者是一种更正确/更优雅的方式来处理这种情况?

I can then decode the JSON via the UserWrapper, and the User is decoded also. It seems like a lot of redundant code since I'll need an extra wrapper on every type I have. Is there a way to avoid this wrapper pattern or a more correct/elegant way of handling this situation?

推荐答案

您可以使用字典进行解码:用户组合然后提取出用户对象.例如

You could decode using a dictionary: user combination then extract out the user object. e.g.

struct User: Codable {
    let id: Int
    let username: String
}

let decoder = JSONDecoder()
let userDictionary = try decoder.decode([String: User].self, from: jsonData)

这篇关于Swift 4 Codable;如何使用单个根级密钥解码对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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