In the mind

.

This is an account of swift’s problems with codable models.

Began to show

{json structure"foods": [{"id": "100261764"."nm": Light cheesecake."pic": "http://test.com/2e/aaa.jpg"
        },
        {
           
            "id": "100445983"."nm": Tinrry+ Chiffon Cake (6-inch Recipe) (Basic, super detailed tutorial)}]."id": "40072"."nm": "Afternoon tea"
}
Copy the code
Model structurestruct TopicDto: Codable.Identifiable {
    let id: String
    let nm: String
    let foods: [FoodDto]}struct FoodDto: Codable.Identifiable {
    let id: String
    let pic: String
    let nm: String
}

Copy the code
parsinglet jsonData ="". The data (using: utf8)let decoder = JSONDecoder(a)let topic = try? decoder.decode(TopicDto.self, from: jsonData)
if topic = = nil {
    print("Model resolution failed")}Copy the code
The wrong way

Since parsing a [TopicDto] array structure, we did not notice that topic parsing failed. We wrongly thought that the foods nodes of the topic node were empty, and then went up

struct TopicDto: Codable.Identifiable {
    let id: String
    let nm: String
    let foods: [FoodDto]

    enum CodginKeys: String.CodingKey { case id, nm, foodarr }
    enum FoodKeys: String.CodginKey { case foods }

    init(from decoder: Decoder) throws {
        let values = try decoder.container(keyedBy: CodingKeys.self)
        id = try values.decode(String.self, forKey: .id)
        nm = try values.decode(String.self, forKey: .nm)

        let foodDicts = try values.nestedContainer(keyedBy: FoodKeys.self, forKey: .foodarr)

    }
}
Copy the code

It’s one mistake after another.

Identify problems correctly

When I found that the parsed topic was nil, I had an insight and started to check the comparison between my model structure and JSON data (here is the simplified structure) to guess whether it was caused by the philosophical problem of “something and nothing”.

When I tried to remove all the PIC members of FoodDto, I could correctly resolve the topic. Foods under the colleague topic model have two food

struct FoodDto: Codable.Identifiable {
    let id: String
    let pic: String?
    let nm: String
}
Copy the code

After modifying FoodDto, the problem is solved.

Thank you

Encoding and Decoding Custom Types

Using JSON with Custom Types

UsingJSONWithCustomTypes-playground