0

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
}
1
  • 1
    Looks like you have an array of TutorialModel in what you've printed for the console, but it's hard to tell where you're printing that, since you don't include that in your code. You could edit your post to include the actual JSON if you need assistance with it. You could also paste it into app.quicktype.io and compare your model. Commented Mar 5, 2022 at 23:19

1 Answer 1

0

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
 }
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot. That was my mistake

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.