Decoding Error: typeMismatch - Expected to decode Dictionary<String, String> but found a string/data instead

Got this API response:

...
"campaigns": [
            {
                "id": 2,
                "name": {
                    "en": "Example Campaign",
                    "de": "Beispiel Kampagne"
                },
                "targetagegroup": null,
                ...

I'm decoding into:

class Campaign: Codable {

    var id: Int?
    var name: [String:String]?
    var targetagegroup: String?
    ...
}

All works fine. But with this response:

...
 "someproperty": null,
 "slogan": {
     "en": "foo",
     "de": "bar"
 },
 "someotherproperty": null,
 ...

When decoding into:

class User: Codable {
 ...
 var someproperty: String?
 var slogan: [String:String]?
 var someotherproperty: String?
 ...
}

I'm getting the following error:

typeMismatch(Swift.Dictionary<Swift.String, Swift.String>, Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "detailresponse", intValue: nil), CodingKeys(stringValue: "element", intValue: nil), _JSONKey(stringValue: "Index 0", intValue: 0), CodingKeys(stringValue: "participants", intValue: nil), _JSONKey(stringValue: "Index 1", intValue: 1), CodingKeys(stringValue: "slogan", intValue: nil)], debugDescription: "Expected to decode Dictionary<String, String> but found a string/data instead.", underlyingError: nil))

Not sure why decoding a User gives me issues with when decoding a Campaign doesn't.

The error clearly says

The value for key slogan at index 1 of array participants at index 0 of array element in detailresponse

is a string rather than the expected dictionary.

Please check the JSON

decode json from http get request, dataTask(with: url, completionHandler: {data, response, error in do { let json = try ? localizedDescription)") } let decoder = JSONDecoder() let temp = try! decoder .decode(MonsterInfo.self, from: typeMismatch(Swift. intValue: nil)], debugDescription: "Expected to decode Dictionary<String, Int> but found an array instead. The error is clear: The value for results is an array and nestedContainers expects a dictionary. To decode the user array you need an umbrella struct outside of the Core Data classes. While decoding Root the init method in User is called for each array item. To use nestedContainers you have to separate the CodingKeys.

Your second object doesn't appear to be valid JSON.

{
    "someproperty": null,
    "slogan": {
        "en": "foo",
        "de": "bar"
    },
    "someotherproperty": null,
}

That decodes for me just fine.

Swift.DecodingError.typeMismatch(Swift.Array<Any>, Swift , expression unexpectedly raised an error: Swift. Swift.DecodingError. " Expected to decode Array<Any> but found a dictionary instead." Context( codingPath: [], debugDescription: "Expected to decode Array but found a� JSONDecoder - “Expected to decode Dictionary<String, Any> but found a string/data instead.” 1 Swift - “Expected to decode Array<Any> but found a dictionary instead.”

Like I said in my comment, i think you receive a plain string into your "slogan" property in your JSON result. And not an object like you describe.

I tried in a playground :

struct Campain: Codable {
    var slogan: [String:String]?
}

let json = "{\"slogan\": \"\"}"
let campain = JSONDecoder().decode(Campain.self, from: json.data(using: .utf8)!)
print(campain)

Gives me the error :

DecodingError
  ▿ typeMismatch : 2 elements
    - .0 : Swift.Dictionary<Swift.String, Swift.String>
    ▿ .1 : Context
      ▿ codingPath : 1 element
        - 0 : CodingKeys(stringValue: "slogan", intValue: nil)
      - debugDescription : "Expected to decode Dictionary<String, String> but found a string/data instead."
      - underlyingError : nil

If i put a real object in the JSON (same as your example), it works.

Decoding a dictionary with a custom type (not String) as key, typealias Dict = [String: String] do { let decoder = JSONDecoder() let string Fatal error: Error raised at top level: Swift.DecodingError.typeMismatch(Swift. " Expected to decode Array<Any> but found a dictionary instead. Hello delawaremathguy & NigelGee , your reply is highly appreciated. I revised the code to be let friends: [Friends] instead of let friends: Friends and still the same. . However, also applied the below code as per delawaremathguy suggestion, now i get this message: JSON decode failed: The data couldn’t be read because it isn’t in the correct

Expected to decode Dictionary<String, Any> but found an array , Expected to decode Dictionary but found an array instead with Nested Containers - json. a Core Data Model: required convenience public init(from decoder: Decoder) throws forKey: .results) Here's the complete error: typeMismatch(Swift. The following are 30 code examples for showing how to use json.decoder.JSONDecodeError().These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

JSON Decoding Error - typeMissmatch Swift 4 - json - html, JSON Decoding Error - typeMissmatch Swift 4 - json. typeMismatch on decodable Type when the type is correct "credit_count", intValue: nil)], debugDescription: "Expected to decode Dictionary<String, Any> but found a number instead. Decode definition, to translate (data or a message) from a code into the original language or form. See more.

The easiest and suggested way is to create separate model for each dictionary or model that is in JSON. Here is what I do //Model for dictionary **Metadata** struct Metadata: Codable { var link_id: String? var buy_count: Int? } //Model for dictionary **Customer** struct Customer: Codable { var object: String? var id: String?

Comments
  • Are you sure that you do not receive the slogan property as a plain JSON string instead of an object ?
  • You seem to have elided much of the relevant information that likely makes Campaign and User different in your real code, but identical here. Build a playground that demonstrates the problem in a way that you can post and we can reproduce it. (In many cases, building that example will show you the problem anyway.)
  • @RobNapier: I've abstracted it because everything works just fine if I comment out var slogan: [String:String]? in class User. So I've concluded that the rest should not be relevant. Would you agree?
  • @jtouzy: I'm receiving it exactly as it's shown above. Copy and paste from the response.
  • Please show the entire error message. Most likely in one of the items in the array slogan is a string rather than a dictionary.
  • I understandt that. But this here "slogan": { "en": "foo", "de": "bar" }, is copy paste from the response. So I don't understand why that would be a string. That's a dictionary.
  • Check the whole (coding) path. Index 0 is the first item and index 1 is the second item. Actually if the decoder throws an error then there is a string.
  • Many thanks!!! You were right. slogan for the second participant was indeed a string - and I was looking at the first participant...