代码之家  ›  专栏  ›  技术社区  ›  Nickolas de Luca Alberton

如何在Swift 4中处理嵌套JSON

  •  0
  • Nickolas de Luca Alberton  · 技术社区  · 8 年前

    我正在编写自己的修饰版“hello world”,并决定处理来自URL的JSON响应。 我读过很多关于如何处理的帖子 JSON 具有 Codable 但是我不知道如何为这个嵌套的JSON创建可编码的结构。

    {
        "acumulado": "sim",
        "cidades": [],
        "data": "2018-05-02",
        "ganhadores": [
            0,
            91,
            6675
        ],
        "numero": 2036,
        "proximo_data": "2018-05-05",
        "proximo_estimativa": 22000000,
        "rateio": [
            0,
            21948.81,
            427.46
        ],
        "sorteio": [
            7,
            8,
            19,
            23,
            27,
            58
        ],
        "valor_acumulado": 18189847.7
    }
    

    这是从API返回的JSON示例,如何创建可编码结构来处理它? 附言:我知道有很多帖子都涉及到这一点,但我不知道如何让它与我的样本一起工作。

    1 回复  |  直到 8 年前
        1
  •  1
  •   Sulthan    8 年前

    首先,您的JSON并不是真正嵌套的:

    struct MyObject: Codable {
       let acumulado: String
       let cidades: [String] // ?? hard to know what data type is there
       let numero: Int
       let proximo_data: String
       let proximo_estimativa: Int
       let rateio: [Double]
       let sorteio: [Int]
       let valor_acumulado: Double
    }
    

    字典中可以省略的每个值都应该是可选的(例如。 let proximo_data: String? )

    您还可以使用 CodingKeys 要重命名变量,请执行以下操作:

    struct MyObject: Codable {
       let acumulado: String
       let cidades: [String] // ?? hard to know what data type is there
       let numero: Int
       let proximoData: String
       let proximoEstimativa: Int
       let rateio: [Double]
       let sorteio: [Int]
       let valorAcumulado: Double
    
       enum CodingKeys: String, CodingKey {
         case acumulado
         case cidades
         case proximoData = "proximo_data"
         case proximoEstimativa = "proximo_estimativa"
         case rateio
         case sorteio
         case valorAcumulado
       }
    }