【问题标题】:Is there a way to decode JSON into struct without creating top level structure有没有办法在不创建顶级结构的情况下将 JSON 解码为结构
【发布时间】:2021-08-10 03:02:56
【问题描述】:

我需要一种将 JSON 解码为 Swift 结构的方法,但不是从顶级 JSON 开始解码。

例如,我有一些这样的 JSON 响应

{"response": { "name": "John", "id": 2"} }

实际上,我只需要包含 name 和 id 字段的嵌套对象,我不需要结构中的顶级“响应”。

所以问题是:
我可以在没有“响应”顶层的情况下解码该嵌套对象吗?
但如果我能检查一下,如果这个顶级“响应”存在,然后解码,那就太好了。

我的 API 返回内部带有响应对象的顶级“响应”或内部带有错误对象的顶级“错误”,因此我必须在解码之前检查是否有错误或响应。

【问题讨论】:

  • 给出你尝试的示例代码

标签: json swift struct nested jsondecoder


【解决方案1】:

您需要包含所有内容,但如果您不想从顶层创建结构,您可以将其解码为字典

struct Person: Decodable {
    let id: Int
    let name: String
}

do {
    let result = try JSONDecoder().decode([String: Person].self, from: data)
    
    if let response = result["response"] {
        print(response)
    } else if let error = result["error"] {
        print(error)
    } else {
        print("Unknown result from API call")
    }
}

【讨论】:

    【解决方案2】:

    您可以尝试使用ObjectMapper 并这样做:Mapping of Nested Objects

    func mapping(map: Map) {
        name <- map["response.name"]
        id   <- map["response.id"]
    }
    

    【讨论】:

      猜你喜欢
      • 2017-04-05
      • 2019-10-13
      • 1970-01-01
      • 2017-10-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多