JSON-数据正在加载,但似乎无法解码

JSON-Data be loaded, but seems that it can't decoded

我有以下代码解码 JSON-String:

        guard let newTutorial = try? JSONDecoder().decode(TutorialModel.self, from: data) else { return }
        DispatchQueue.main.async { [weak self] in
            self?.tutorials.append(newTutorial)
        }

在控制台中,字符串将如下所示:

Successfully Downloaded Data
Optional("[\n    {\n        \"id\": 1,\n        \"headline\": \"How to messure the T8\",\n        \"descriptiontext\": \"Learn how to messure the T8\"\n    },\n    {\n        \"id\": 2,\n        \"headline\": \"How to messure the Tiger 5000s\",\n        \"descriptiontext\": \"Learn how to messure the Tiger 5000s\"\n    }\n]")

来自服务器的原始字符串是:

[
{
    "id": 1,
    "headline": "How to messure the T8",
    "descriptiontext": "Learn how to messure the T8"
},
{
    "id": 2,
    "headline": "How to messure the Tiger 5000s",
    "descriptiontext": "Learn how to messure the Tiger 5000s"
}
]

而当我喜欢查看数据时,数组中没有数据:

    List {
        ForEach (vm.tutorials) { tutorial in
            VStack {
                Text(tutorial.headline)
                    .font(.headline)
                Text(tutorial.descriptiontext)
                    .foregroundColor(.gray)
            }
        }
    }

难道这个JSON-字符串不正确?

结构是:

struct TutorialModel: Identifiable, Codable {
    let id: Int
    let headline, descriptiontext: String
}

您的 json 数据似乎是正确的。它是一个 TutorialModel 的数组, 不是一个 TutorialModel,因此将响应解码为数组,例如:

guard let newTutorial = try? JSONDecoder().decode([TutorialModel].self, from: data) else { return }
 DispatchQueue.main.async { [weak self] in
     self?.tutorials = newTutorial
 }