Swift 4 Codable decoding json

后端 未结 3 1464
遇见更好的自我
遇见更好的自我 2021-02-09 07:37

I\'m trying to implement the new Codable protocol, so I added Codable to my struct, but am stuck on decoding the JSON.

Here\'s

3条回答
  •  走了就别回头了
    2021-02-09 08:32

    If your JSON has a structure

    {"themes" : [{"title": "Foo", "answer": 1, "question": 2},
                 {"title": "Bar", "answer": 3, "question": 4}]}
    

    you need an equivalent for the themes object. Add this struct

    struct Theme : Codable {
        var themes : [Question]
    }
    

    Now you can decode the JSON:

    if let decoded = try? JSONDecoder().decode(Theme.self, from: data) {
        print("decoded:", decoded)
    } else {
        print("Not working")
    }
    

    The containing Question objects are decoded implicitly.

提交回复
热议问题