gpt4 book ai didi

json - Swift Codable 解码更改 JSON 并忽略某些字段

转载 作者:搜寻专家 更新时间:2023-11-01 06:52:20 26 4
gpt4 key购买 nike

我有一些 REST API,它返回 JSON。此 API 被不止一项服务(移动、网络等)使用,它返回 JSON,其中的字段比我需要的多,其中一些额外字段可以每周更改一次。例如我有这样的 JSON:

{ "name": "Toyota Prius", "horsepower": 134, "mileage": 123241, "manufactured": 2017, "location": "One city", "origin": "Japan",
"convert": true //more properties follows... }

在移动应用程序中,我只需要解码字段:名称、马力和制造日期,其余的可以忽略。还有一些像 origin 这样的字段以前不存在,但是几天前添加的。

问题是如果 JSON 中有一些不影响我在应用程序中的模型的更改,如何编写不会破坏的防弹解码器?此外,我在服务器的输出 JSON 中一无所知,我无法影响它。我只是获取数据,我必须处理我得到的数据。

我已经为 Playground 写了一些实验代码(汽车没有打印出来):

import UIKit

struct Car: Codable
{
let name: String
let horsePower: Int
let selected: Bool //this is used as additional property inside my app to mark selected cars
let index: Int //this is used as additional property inside my app for some indexing purposes

enum CodingKeys: String, CodingKey
{
case name
case horsePower = "horsepower"
case selected
case index
}

init(from decoder: Decoder) throws
{
let values = try decoder.container(keyedBy: CodingKeys.self)

selected = false
index = 0

name = try values.decode(String.self, forKey: .name)
horsePower = try values.decode(Int.self, forKey: .horsePower)
}
}

let json = "{\"name\": \"Toyota Prius\",\"horsepower\": 134, \"convert\", true}"

let data = json.data(using: .utf8)

if let car = try? JSONDecoder().decode(Car.self, from: data!)
{
//does not print... :(
print(car)
}

我想在我的示例中打印汽车,但大多数情况下都有一个有效的验证代码,如果 JSON 发生更改,该代码不会中断。还有办法以某种方式获得解码错误描述吗?我知道 Apple 文档中有很多内容,但大多数内容对我来说太困惑了,我找不到任何有用的示例来解决我的问题。

最佳答案

首先从不 尝试? JSONDecoder...catch 总是错误并打印出来。 DecodingErrors 非常具有描述性。他们会准确地告诉您哪里出了问题。

在你的例子中你会得到

"The given data was not valid JSON. ... No value for key in object around character 52."

convert\"

之后是错误的逗号(而不是冒号)

要仅解码特定的键,请相应地声明 CodingKeys 并删除 init 方法。 selectedindex 很可能是可变的,因此将它们声明为具有默认值的变量。

如果后端更改 JSON 结构,您将收到错误消息。不管解析 API 是什么,解码过程都会中断。

struct Car: Codable
{
let name: String
let horsePower: Int
let convert : Bool

var selected = false
var index = 0

enum CodingKeys: String, CodingKey {
case name, horsePower = "horsepower", convert
}
}

let json = """
{"name":"Toyota Prius","horsepower":134,"convert":true}
"""

let data = Data(json.utf8)

do {
let car = try JSONDecoder().decode(Car.self, from: data)
print(car)
} catch { print(error) }

关于json - Swift Codable 解码更改 JSON 并忽略某些字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56341527/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com