Search code examples
iosjsonswiftcodablejsondecoder

Difficulty parse integer value in JSON using JSON Decoder in Swift


I am trying to decode some JSON from an API that looks like this (foo is short for a list of properties):

{"page":1,"total_results":10000,"total_pages":500,"results":[{"foo":"bar"},{"foo":"bar2"},{"foo":"bar3"}]}

The struct recommended by quicktype.io which looks correct to me too is:

struct ObjectsReturned: Codable {
    let page, totalResults, totalPages: Int
    let results: [Result]

    enum CodingKeys: String, CodingKey {
        case page
        case totalResults = "total_results"
        case totalPages = "total_pages"
        case results
    }
}

// MARK: - Result
struct Result: Codable {
    let foo: String
}

However, when I try to decode, although it is able to handle page, it throws an error on total_results as follows:

typeMismatch(Swift.Dictionary<Swift.String, Any>, Swift.DecodingError.Context(codingPath: [_DictionaryCodingKey(stringValue: "total_results", intValue: nil)], debugDescription: "Expected to decode Dictionary<String, Any> but found a number instead.", underlyingError: nil))

What could be the reason for this error and how can I fix it?

Thanks for any suggestions.

Note:

Decoding is via:

do {
                            let mything = try JSONDecoder().decode([String:ObjectReturned].self, from: data)
                        } catch {
                            print(error)
                        }

Solution

  • You are trying to decode the wrong type. Your root object is a single ObjectsReturned instance and not a [String:ObjectsReturned].

    let mything = try JSONDecoder().decode(ObjectsReturned.self, from: json2)