【问题标题】:How can I convert Json into 2D array?如何将 Json 转换为二维数组?
【发布时间】:2018-09-28 08:44:46
【问题描述】:

如果我有这样的 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 中是不可能的,请告诉我。谢谢!

【问题讨论】:

  • 问题不在于它是一维还是二维数组,问题是你的数组有不同的类型。
  • @regina_fallangi 我可以解码不同的 Json,例如 {"i": ["123",456]} 其中包括 String 和 Int,但只有在数组内有数组时才能工作
  • 那个问题已经有了答案:stackoverflow.com/questions/48749302/…
  • @regina_fallangi 这个好像不能回答我的问题 QQ
  • 如果你真的不知道类型(如果它们真的是Any),并且无法更改从服务器发送的内容 - 你应该考虑将你的 json 转换为字典和数组 -看JSONSerialization.jsonObject(with: options: )

标签: arrays json swift decode codable


【解决方案1】:

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

例如:

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)")
    }


}

【讨论】:

  • 在这种情况下您可以删除CodingKeys
猜你喜欢
  • 1970-01-01
  • 2014-12-27
  • 2015-10-15
  • 2010-11-20
  • 1970-01-01
  • 1970-01-01
  • 2011-07-05
  • 2019-07-09
  • 2015-07-16
相关资源
最近更新 更多