Ios 如何使用Swift 4 Codable处理JSON格式不一致?
我需要解析其中一个字段值为数组的JSON:Ios 如何使用Swift 4 Codable处理JSON格式不一致?,ios,json,swift4,codable,jsondecoder,Ios,Json,Swift4,Codable,Jsondecoder,我需要解析其中一个字段值为数组的JSON: "list" : [ { "value" : 1 } ] 或空字符串,以防没有数据: "list" : "" 不太好,但是我不能改变格式 我正在考虑将我的手动解析转换为JSONDecoder和Codablestruct 如何处理这种令人讨厌的不一致性?您需要尝试以一种方式对其进行解码,如果失败,则以另一种方式对其进行解码。这意味着您不能使用编译器生成的解码支持。你必须手工做。如果要进行完整的错误检查,请执行以下操作:
"list" :
[
{
"value" : 1
}
]
或空字符串,以防没有数据:
"list" : ""
不太好,但是我不能改变格式
我正在考虑将我的手动解析转换为JSONDecoder
和Codable
struct
如何处理这种令人讨厌的不一致性?您需要尝试以一种方式对其进行解码,如果失败,则以另一种方式对其进行解码。这意味着您不能使用编译器生成的解码支持。你必须手工做。如果要进行完整的错误检查,请执行以下操作:
import Foundation
struct ListItem: Decodable {
var value: Int
}
struct MyResponse: Decodable {
var list: [ListItem] = []
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
do {
list = try container.decode([ListItem].self, forKey: .list)
} catch {
switch error {
// In Swift 4, the expected type is [Any].self, but I think it will be [ListItem].self in a newer Swift with conditional conformance support.
case DecodingError.typeMismatch(let expectedType, _) where expectedType == [Any].self || expectedType == [ListItem].self:
let dummyString = try container.decode(String.self, forKey: .list)
if dummyString != "" {
throw DecodingError.dataCorruptedError(forKey: .list, in: container, debugDescription: "Expected empty string but got \"\(dummyString)\"")
}
list = []
default: throw error
}
}
}
enum CodingKeys: String, CodingKey {
case list
}
}
如果不想进行错误检查,可以将init(from:)
缩短为:
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
list = (try? container.decode([ListItem].self, forKey: .list)) ?? []
}
测试1:
let jsonString1 = """
{
"list" : [ { "value" : 1 } ]
}
"""
print(try! JSONDecoder().decode(MyResponse.self, from: jsonString1.data(using: .utf8)!))
产出1:
MyResponse(list: [__lldb_expr_82.ListItem(value: 1)])
测试2:
let jsonString2 = """
{
"list" : ""
}
"""
print(try! JSONDecoder().decode(MyResponse.self, from: jsonString2.data(using: .utf8)!))
产出2:
MyResponse(list: [])
我同意,你应该给创建该web服务的人一记兴奋剂。如果没有列表,他们至少应该返回
“list”:null
,而不是更改结果的类型!但是,为了回答您的问题,您必须编写一个init(from:)抛出
方法,手动尝试解码列表
,当它是一个字符串时进行优雅的处理。请参阅init(from:)
示例。如果手动解析有效,请不要更改它。Codable
(采用协议,你就完成了)的魔力只有在JSON是一致的情况下才会发生。@Rob这只是《纽约时报》的API.Lol。这仍然是错误的。它值得一个bug报告。出于好奇,您正在使用哪个端点?@Rob endpoint:这没有我的个人apikey,可以很容易地从它的“{results”[{“media”:,…},…},…]}
中获得,谢谢您的回答!但我会坚持我的手动遍历对象树,因为它相当简单且易于遵循。进一步思考:因为这是一个丑陋/愚蠢的格式错误,我倾向于修复JSON输入字符串(用“list”:“
”替换“list”:[]
”)。我知道它不太通用,并且假设“list”:“
不会出现在其他地方。这样就可以使用可解码的。对一个丑陋问题的一个小的务实的解决方案;我喜欢这样。