如何将 Json 转换为二维数组?

How can I convert Json into 2D array?

如果我得到这样的Json:

{ "i": [ "0", [123]] }

有什么方法可以解码上面的二维数组吗?

class ModelA: Codable{
    var i: [String]?
    var temp: [Any] = []

    enum CodingKeys: String, CodingKey {
        case i = "i"
    }

    required init(from decoder: Decoder) throws {
        let value = try decoder.container(keyedBy: CodingKeys.self)
        temp = try value.decode([Any].self, forKey: .i)
    }
}

用法:

public func printJsonData(){

    let jsonData: Data = """
    {
        "i": [ "0", [123]]
    }
    """.data(using: .utf8)!

    if let model = try? JSONDecoder().decode(ModelA.self, from: jsonData){
        print(model.temp)
    }else{
        print("no data")
    }
}

我试过数组 [Any] 在这里成功运行, 但找不到任何在二维数组中转换的方法。 如果有人知道如何解决这个问题,或者知道这在 Swift4.2 中是不可能的,请告诉我。谢谢!

如果您知道数组值的可能数据类型,也许您可​​以尝试使用枚举而不是 [=15= 表示的可能值(在本例中为 String[Int]) ].

例如:

enum ArrayIntOrString: Decodable {

    case string(String)
    case arrayOfInt([Int])

    init(from decoder: Decoder) throws {

        if let string = try? decoder.singleValueContainer().decode(String.self) {
            self = .string(string)
            return
        }

        if let arrayOfInt = try? decoder.singleValueContainer().decode([Int].self) {
            self = .arrayOfInt(arrayOfInt)
            return
        }

        throw ArrayIntOrStringError.arrayIntOrStringNotFound
    }

    enum ArrayIntOrStringError: Error {
        case arrayIntOrStringNotFound
    }
}

并在您的模型中声明它:

class ModelA: Decodable {

    var i: [ArrayIntOrString]?

    enum CodingKeys: String, CodingKey {
        case i = "i"
    }   
}

用法

public func printJsonData() {

    let jsonData: Data = """
    {
        "i": [ "0", [123]]
    }
    """.data(using: .utf8)!

    do {
        let model = try JSONDecoder().decode(ModelA.self, from: jsonData)
        print(model.i)
    } catch let err {
        print("no data \(err)")
    }


}