ios - Decodable value String or Bool
问题描述
I'm currently working with a bad designed JSON Api... This returns always a value (eg. String, Int, Double...) or false(not null).
What is the best way to handle this with decodable, as Any is not supported by Codable?
A key can look like this:
{
"key": "Test",
}
Or like this(I know, should be null instead of false):
{
"key": false,
}
And this is not possible:
struct Object: Decodable {
let key: Any?
}
解决方案
您可以创建一个通用包装类型,如果键的值为 ,则分配nil
给一个Optional
值false
,否则它会解码该值。然后,您可以将它们包装在此包装器中,而不是存储实际类型。
struct ValueOrFalse<T:Decodable>: Decodable {
let value:T?
public init(from decoder:Decoder) throws {
let container = try decoder.singleValueContainer()
let falseValue = try? container.decode(Bool.self)
if falseValue == nil {
value = try container.decode(T.self)
} else {
value = nil
}
}
}
struct RandomJSONStruct: Decodable {
let anInt:ValueOrFalse<Int>
let aString:ValueOrFalse<String>
}
let noValueJson = """
{
"anInt": false,
"aString": "Test"
}
"""
do {
print(try JSONDecoder().decode(RandomJSONStruct.self, from: noValueJson.data(using: .utf8)!))
} catch {
print(error)
}
推荐阅读
- node.js - 使用 mongoose 和 nodejs 在 mongodb 中保存模型数组
- c# - 如何始终使用串行端口从 USB 读取秤重量
- flutter - 在 Flutter/Dart 中返回空快照的 Map 的 Cloud Firestore 查询
- javascript - 如何使用 .exec() 访问/替换全局匹配正则表达式中的捕获组?
- reactjs - Flask 中的 React 选择值
- php - 在 codeigniter 4 中:调用 findAll() 和 asArray()->findAll() 有什么区别?
- c++ - 不能使 C++ 编译器有条件地使用类型特征引发错误
- python-3.x - KeyError:使用 Google Cloud Vision API 进行 OCR 时出现“textAnnotations”
- c++ - VS2017:C++:通过 const std::map 迭代
: 链接错误 - javascript - 可以使用 Eve 在 REST 调用中指定要在 MongoDB 中搜索的文本索引字段吗?