【问题标题】:Parse JSON using codable and CodingKeys swift使用可编码和 CodingKeys swift 解析 JSON
【发布时间】:2020-08-15 17:10:41
【问题描述】:

我尝试了很多教程,但都解决不了。

我有这样的 JSON 结构。

    {
"Region":[
   {
      "head":[
         {
            "total_count":572888
         },
         {
            "RESULT":{
               "CODE":"000",
               "MESSAGE":"Success."
            }
         },
         {
            "api_version":"1.0"
         }
      ]
   },
   {
      "row":[
         {
            "COM_NAME":"company",
            "TYPE_CD":null,
            "BIZ_NM":null,
            "TYPE_NM":null,
            "TELNO":"111-1111-1111",
            "MNY_NM":null,
            "POSBL_YN":null,
            "DATE":"2018-09-30",
            "ROAD_ADDR":"adrress",
            "ZIP_CD":"10303",
            "LOGT":"126.80090346",
            "LAT":"37.673069059",
         }
        ]
    }
]

}

我想做的是从行部分解码一些属性。

所以我创建了一些这样的结构。

struct List: Decodable {
    let Region: [Stores]
}


struct Stores: Decodable {
    let row: [StoreInfo]
}

struct StoreInfo: Decodable {
    let COM_NAME: String?
    let TYPE_NM: String?
    let TELNO: String?
    let DATE: String?
    let ROAD_ADDR: String?
    let LOGT: String?
    let LAT: String?
}

然后像这样用 Jsondecoder 解码。

 let decodedData = try JSONDecoder().decode(List.self, from: data)
 print(decodedData)

我收到这样的错误。

    keyNotFound(CodingKeys(stringValue: "Region", intValue: nil),
 Swift.DecodingError.Context(codingPath: [], debugDescription: "No value associated with key CodingKeys(stringValue: \"Region\", intValue: nil) 
(\"Region\").", underlyingError: nil))

如何正确解码?

【问题讨论】:

    标签: json swift codable


    【解决方案1】:

    我使用了 store 和 store info 作为可选,并使用 Codable 创建了结构,它起作用了。

    struct List: Codable {
        let Region: [Stores]?
    }
    
    
    struct Stores: Codable {
        let row: [StoreInfo]?
    }
    
    struct StoreInfo: Codable {
        let COM_NAME: String?
        let TYPE_NM: String?
        let TELNO: String?
        let DATE: String?
        let ROAD_ADDR: String?
        let LOGT: String?
        let LAT: String?
    }
    
    

    【讨论】:

      【解决方案2】:

      数组“Region”包含不同的类型,在swift中它会被声明为[Any],所以你需要将row声明为可选,所以当解码器找到并尝试解码元素“head”时,它会忽略它元素并解码下一个元素。

      struct Stores: Decodable {
          let row: [StoreInfo]?
      }
      

      PS
      您发布的错误不是从发布的代码生成的,发布代码的真正错误是

      keyNotFound(CodingKeys(stringValue: "row", intValue: nil), Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "Region", intValue: nil), _JSONKey(stringValue: "Index 0", intValue : 0)], debugDescription: "No value associated with key CodingKeys(stringValue: \"row\", intValue: nil) (\"row\").", underlyingError: nil))

      DS

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-02-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-05-31
        • 1970-01-01
        相关资源
        最近更新 更多