Swift 4 Codable decoding json

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

提交回复
热议问题