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 struct ,可以解码user键:

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

因为idusernameuser的属性,而不是在根级别,所以我需要创建一个如下的包装器类型:

struct UserWrapper: Codable {
  let user: User
}

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

推荐答案

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)

Json相关问答推荐

Vega-Lite时钟(使用Vega-Lite中的计时器)

如何在使用GO时检测JSON中不需要的字段?

在scala中将字符串列转换为 struct 的JSON映射

Jolt需要将缺少的值设置为空并保持相同的位置

使用JQ从jsonl文件中删除具有匹配键/值的行

go 语言中的 JSON 到 XML

Android 如何判断小时时间是否在两个时间之间?

如何使NiFi将数据库单列中的多个值转化为Solr索引中的数组?

Oracle json 对象的最后一个值不在引号中

将环境变量值从 yaml 传递到 json

Golang 解组行为:字段过多?

如何在 Postman 中匹配 json 响应中的内容?并可视化

使用 Jolt 变换将平面 json 转换为具有多个数组的嵌套 Json

如何使用法语口音对数组进行 json_encode?

Android 上的 JSON - 序列化

使用 JSON 的 javascript 深拷贝

使用 JSONObject 在 Java 中为以下 struct 创建嵌套 JSON 对象?

获取一个数字的 PHP 对象属性

为什么 RestTemplate 不将响应表示绑定到 PagedResources?

如何用接口序列化一个类?