Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[
{
    "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
}

>Solution :

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
 }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading