如何使用Swift 4 Codable处理JSON格式不一致?

时间:2018-02-24 20:24:39

标签: ios json swift4 codable jsondecoder

我需要解析JSON,其中一个字段值是一个数组:

"list" :
[
    {
        "value" : 1
    }
]

或空字符串,以防没有数据:

"list" : ""

不太好,但我无法改变格式。

我正在考虑将我的手动解析转换为JSONDecoderCodable struct

如何处理这种令人讨厌的不一致?

1 个答案:

答案 0 :(得分:2)

您需要尝试以一种方式对其进行解码,如果失败,则以另一种方式对其进行解码。这意味着您无法使用编译器生成的解码支持。你必须手工完成。如果您想要完整的错误检查,请执行以下操作:

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: [])