[英]How to make sure that all JSON fields are presented in a Swift Decodable model?
Let's imagine a third-party JSON API returning a model like this: 让我们想象一个第三方JSON API返回如下模型:
{
"key1": "Hello"
}
So we describe it as follows: 因此,我们将其描述如下:
struct Model: Codable {
var key1: String
}
Eventually the JSON model gets a new field… 最终,JSON模型获得了一个新领域……
{
"key1": "Hello",
"key2": {
"key3": "World"
}
}
…and the old Model
still works, but it misses a new property key2
. …并且旧
Model
仍然有效,但是它错过了新的属性key2
。
Is there any way to verify that all JSON keys are presented in the Decodable model? 有什么方法可以验证在Decodable模型中是否提供了所有 JSON密钥?
Here is a way to do it by getting all the keys in the json message by using JSONSerialization
and then comparing them to the key(s) in the parsed data using reflection 这是一种通过使用
JSONSerialization
获取json消息中的所有键,然后使用反射将它们与解析数据中的键进行比较的方法
This code only compares the count, a more thorough check should verify each individual key 该代码仅比较计数,更彻底的检查应验证每个单独的密钥
do {
let dictionary = try JSONSerialization.jsonObject(with: data) as? [String: Any]
let result = try JSONDecoder().decode(Model.self, from: data)
if let keys = dictionary?.keys {
let mirror = Mirror(reflecting: result)
if keys.count != mirror.children.count {
print("Wrong number of keys")
//throw SomeError
}
}
//handle result
} catch {
print(error)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.