[英]How to handle JSON format inconsistencies with Swift 4 Codable?
我需要解析其中一個字段值是數組的JSON:
"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: [])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.