-2

I get this error:

"typeMismatch(Swift.Dictionary<Swift.String, Any>, Swift.DecodingError.Context(codingPath: [], debugDescription: "Expected to decode Dictionary<String, Any> but found an array instead.", underlyingError: nil))"

In swift while decoding JSON (from django rest framework).

This is the json:

[
    {
        "id": 1,
        "title": "1e todo",
        "description": "1e todo test"
    },
    {
        "id": 2,
        "title": "2e todo",
        "description": "2e todo test"
    }
]

This is the parse function in Swift:

func parseJSON(todoData:Data){
    let decoder = JSONDecoder()
    do{
        let decodedData = try decoder.decode(ToDoData.self, from: todoData)
        fetchedTitle = decodedData.todoitems[1].title
        print(fetchedTitle)

And the Structs in Swift:

import Foundation

struct ToDoData: Decodable {
    //return een list met ToDoData
    let todoitems: [Items]
}

struct Items: Decodable {
    //return een list met ToDoData
    let id: String
    let title: String
    let description: String
}

So its saying found an Array, but how can i get to the "Title" in the JSON file.

Dávid Pásztor
  • 51,403
  • 9
  • 85
  • 116
Sander
  • 29
  • 1
  • 4

1 Answers1

0

Your json seems to be an array of Items, and not an object with a property named todoitems, so do this instead:

let decodedData = try decoder.decode([Items].self, from: todoData)
fetchedTitle = decodedData[1].title

Your ToDoData struct can't be used in this scenario, since your json doesn't contain a property named todoitems.

rodskagg
  • 3,827
  • 4
  • 27
  • 46