JSON Decoder Type Mismatch Error

json parser swift
swift decodingerror keynotfound
json parsing language
quick json parser
codable from json
automatic json parsing
swift decodingerror context
json to decodable

I want to parse JSON using decodable, but I get an error type mismatch like:

Swift.DecodingError.Context(codingPath: [], debugDescription: "Expected to decode Array but found a dictionary instead."

My JSON :

{
  "code": 0,
  "data": {
    "_id": "string",
    "title": "string",
    "images": [
      "string"
    ],
    "shortDesc": "string",
    "desc": "string",
    "price": 0,
    "discountPrice": 0,
    "quantity": 0,
    "category": {
      "name": "string",
      "val": "string"
    },
    "brand": {
      "name": "string",
      "val": "string"
    },
    "variants": [
      {
        "name": "string",
        "value": "string",
        "quantity": 0,
        "variantCode": "string"
      }
    ],
    "stockCode": "string",
    "updatedDate": "2018-06-05T14:04:51.226Z",
    "status": true,
    "isDeleted": true,
    "isNew": true,
    "freeCargo": true,
    "createDate": "2018-06-05T14:04:51.226Z",
    "note1": "string",
    "note2": "string",
    "note3": "string",
    "shop": {
      "name": "string",
      "val": "string"
    }
  },
  "error": "string"
}

MY MODEL:

struct ProductDetail : Decodable {
        let code : Int = 0
        let error : String = ""
        var data : NestedData? = nil
}

NESTED DATA:

struct NestedData : Decodable{
    let _id : String = ""
    let title : String = ""
    let images : [String] = []
    let shortDesc : String = ""
    let desc : String = ""
    let price : Int = 0
    let discountPrice : Int = 0
    let quantity : Int = 0
    let updatedDate : String = ""
    let status : Bool = false
    let isDeleted : Bool = false
    let isNew : Bool = false
    let freeCargo : Bool = false
    let createDate : String = ""
    let note1: String = ""
    let note2: String = ""
    let note3: String = ""
    let variants : [variants]? = nil
    let brand : brand? = nil
    let category :category? = nil
    let shop : shop? = nil

}

OBJECTS:

struct variants : Decodable{
    let name : String
    let val : String
    let quantity : Int
    let variantCode : String
}

struct brand : Decodable{
    let name : String
    let val : String
}

struct category : Decodable{
    let name : String
    let val : String
}

struct shop : Decodable{
    let name : String
    let val : String
}

I don't understand why I get an error, Console says expected array but dictionary found but I don't understand unfortunately.

Ok man I advise you to use quicktype

it will help you to make your model

I use it and this is the Model

struct ProductDetail: Codable {
    let code: Int?
    let data: DataClass?
    let error: String?
}

struct DataClass: Codable {
    let id, title: String?
    let images: [String]?
    let shortDesc, desc: String?
    let price, discountPrice, quantity: Int?
    let category, brand: Brand?
    let variants: [Variant]?
    let stockCode, updatedDate: String?
    let status, isDeleted, isNew, freeCargo: Bool?
    let createDate, note1, note2, note3: String?
    let shop: Brand?

    enum CodingKeys: String, CodingKey {
        case id = "_id"
        case title, images, shortDesc, desc, price, discountPrice, quantity, category, brand, variants, stockCode, updatedDate, status, isDeleted, isNew, freeCargo, createDate, note1, note2, note3, shop
    }
}

struct Brand: Codable {
    let name, val: String?
}

struct Variant: Codable {
    let name, value: String?
    let quantity: Int?
    let variantCode: String?
}

after that, you can use JSONDecoder

Alamofire.request(urlCourses, method: .get, parameters: nil, encoding: URLEncoding.default, headers: nil).responseJSON { (response) in

        switch response.result {

        case .success:

            guard let data = response.data else { return }

            do {

                let productDetail = try? JSONDecoder().decode(ProductDetail.self, from: jsonData)

            } catch let jsonError {

                print("Error serializing json:", jsonError)
            }

        case .failure(let error):

            print(error)
        }
}

Type Mismatch error parsing JSON with Swift Decodable, Let's put some line breaks in your error message to make it understandable: (​Error: typeMismatch(Swift.String, Swift.DecodingError. Type Mismatch when parsing received JSON #17. michaleibl opened this issue Feb 6, 2014 · 5 comments. The received JSON contained "Amount":14.6000000000, which was correctly parsed and given to CDbl for conversion.

I think your code Have no error may be your error in First response so make double check about that

Here is your Model:

  import Foundation

    struct ProductDetail: Codable {
        let code: Int
        let data: NestedData?
        let error: String?
    }

    struct NestedData: Codable {
        let id, title: String
        let images: [String]
        let shortDesc, desc: String
        let price, discountPrice, quantity: Int
        let category:Category
        let brand: Brand
        let variants: [Variant]
        let stockCode, updatedDate: String
        let status, isDeleted, isNew, freeCargo: Bool
        let createDate, note1, note2, note3: String
        let shop: Shop

        enum CodingKeys: String, CodingKey {
            case id = "_id"
            case title, images, shortDesc, desc, price, discountPrice, quantity, category, brand, variants, stockCode, updatedDate, status, isDeleted, isNew, freeCargo, createDate, note1, note2, note3, shop
        }
    }

    struct Brand: Codable {
        let name, val: String
    }
    struct Category: Codable {
        let name, val: String
    }

    struct Shop : Codable{
        let name : String
        let val : String
    }



    struct Variant: Codable {
        let name, value: String
        let quantity: Int
        let variantCode: String
    }


    extension ProductDetail {
        init(data: Data) throws {
            self = try JSONDecoder().decode(ProductDetail.self, from: data)
        }
    }

Here How to Use:

switch response.result {
case .success:
    guard let data = response.data else { return }
    let productDetail = try? ProductDetail.init(data: data){

        //
    }
}

ios - JSON Decoder Type Mismatch Error, Ok man I advise you to use quicktype. it will help you to make your model. I use it and this is the Model struct ProductDetail: Codable { let code: Int? let data:  JSON_ERROR_UTF8: Bad UTF8 character was found. Incorrect encoding. Then, in PHP 5.5, they added three more constants: JSON_ERROR_RECURSION: Recursion detected. JSON_ERROR_INF_OR_NAN: One or more NAN or INF values in the value to be encoded. JSON_ERROR_UNSUPPORTED_TYPE: An unsupported type was found. Using these constants, we can carry out our

Either the response from your server is slightly different than posted above or you have:

let result = try JSONDecoder().decode([ProductDetail].self, from: jsonData)

instead of the correct:

let result = try JSONDecoder().decode(ProductDetail.self, from: jsonData)

I tested the JSON above in a playground and tried to decode using the structs you posted in your code and it worked. If I added [] around ProductDetail then I got the error.

JSON Decoder Type Mismatch Error, I want to parse JSON using decodable, but I get an error type mismatch like: Swift​.DecodingError.Context(codingPath: [], debugDescription: "Expected to decode  let user = Bundle.main.decode(User.self, from: "data.json") The extension is capable of loading any kind of decodable data – your structs, arrays of your structs, and so on. Even better, you can use it to make properties in your types immutable and available as soon as your types are created, like this:

Handling Swift JSONDecoder typeMismatch error while using , If you have a problematic JSON, which can contain number or string for some keys, you can decode object without that property and manually  In this page you will learn about PHP json_last_error() function with examples.

Type mismatch error when parsing JSON with an Integer into a , I have a problem when a property must be a string by semantics, but the JSON passes it as a raw integer. For example I have a class Person  Hi all I have a PHP import script I built about a year ago, been working great! Though all of a sudden, my json_decode has started returning a NULL value resulting in: Warning: Invalid argument

decode json from http get request |Apple Developer Forums, Fatal error: 'try!' expression unexpectedly raised an error: Swift.DecodingError.​typeMismatch(Swift.String, Swift.DecodingError. Parameters. This function has no parameters. Return Values. Returns the error message on success, "No error" if no error has occurred, or FALSE on failure.

Comments
  • I just tested your decodable structs and they seem to work. Perhaps, you're trying to decode an array of ProductDetails – either in JSON string obtained from server or by provided type to JSONDecoder.
  • As a side note: if you provide default values to your codable struct and use autogenerated decoder, the values won't be decoded from JSON and default values will be used instead.
  • maybe you say right , but How can change I default values excatly
  • Thank your answer but didn't work, I guess something wrong another side
  • I tried this before but I didnt get result, I think structure is okay but I dont understand my mistake
  • You show JSON and structs that work. something does not add up. show the code where you decode. if you want a good answer you need to provide all of the information.
  • I have variable var productObserver = Box<ProductDetail>() and I get error here I guess switch response.result { case .success: guard let data = response.data else { return } do { self.decoder.keyDecodingStrategy = .useDefaultKeys let product = try self.decoder.decode(ProductDetail.self, from: data) self.productObserver.value? = product