繁体   English   中英

使用可编码和 CodingKeys swift 解析 JSON

[英]Parse JSON using codable and CodingKeys swift

我试图用许多教程来解决,但不能。

我有这样的 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))

如何正确解码?

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

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

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

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

我将商店和商店信息用作可选,并使用 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?
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM