且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Swift 4 Codable解码json

更新时间:2022-05-16 17:55:45

如果您的JSON具有结构

If your JSON has a structure

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

您需要与 themes 对象等效。添加此结构

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

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

现在您可以解码JSON了:

Now you can decode the JSON:

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

包含的 Question 对象被隐式解码