使用codable和CodingKeys swift解析JSON

时间:2020-05-01 07:45:10

标签: json swift codable

我试图通过许多教程来解决,但没有。

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

如何正确解码?

2 个答案:

答案 0 :(得分:1)

数组“ Region”包含不同的类型,迅速将其声明为[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:“没有与键CodingKeys(stringValue:\“ row \”,intValue:nil)(\“ row \”)。“,underlyingError:nil))相关的值

DS

答案 1 :(得分:0)

我使用store和store信息作为可选内容,并使用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?
}