I have the following code do decode a JSON-String:
guard let newTutorial = try? JSONDecoder().decode(TutorialModel.self, from: data) else { return }
DispatchQueue.main.async { [weak self] in
self?.tutorials.append(newTutorial)
}
In the console the string would be viewed like this:
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]")
The original String, that be from the server is:
[
{
"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"
}
]
And when I like to view the data, then there is no data in the array:
List {
ForEach (vm.tutorials) { tutorial in
VStack {
Text(tutorial.headline)
.font(.headline)
Text(tutorial.descriptiontext)
.foregroundColor(.gray)
}
}
}
Could it be, that this JSON-String is not correct?
The struct is:
struct TutorialModel: Identifiable, Codable {
let id: Int
let headline, descriptiontext: String
}
CodePudding user response:
your json data seems to be correct. It is an array of TutorialModel
,
not one TutorialModel
, so decode the response as an array such as:
guard let newTutorial = try? JSONDecoder().decode([TutorialModel].self, from: data) else { return }
DispatchQueue.main.async { [weak self] in
self?.tutorials = newTutorial
}