Swift 4 Codable decoding json

后端 未结 3 1462
遇见更好的自我
遇见更好的自我 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:25

    You're getting this error because your JSON is likely structured as so:

    {
      "themes": [
        { "title": ..., "question": ..., "answer": ... },
        { "title": ..., "question": ..., "answer": ... },
        { ... }
      ],
      ...
    }
    

    However, the code you wrote expects a [Question] at the top level. What you need is a different top-level type that has a themes property which is a [Question]. When you decode that top-level type, your [Question] will be decoded for the themes key.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-02-09 08:38

    Hello @all I have added the code for JSON Encoding and Decoding for Swift 4.

    Please use the link here

    0 讨论(0)
提交回复
热议问题