ironRoei
ironRoei

Reputation: 2219

JSONDecoder - "Expected to decode Dictionary<String, Any> but found a string/data instead."

So i am trying to decode a json and get this error.

This is the JSON :

{ "SERVERWebSystemInfoGet": { 
        "Return Code" : 0,
        "Return String" : "No Error",
        "Info" : "{\"IT\":\"IT109200310_0\",\"MAC\":\"00:40:7F:41:F8:81\",\"UUID\":\"uuid:858fba00-d3a0-11dd-a001-00407f41f881\",\"SN\":\"ENG031\",\"ModelNumber\":\"DH-390 2MP\",\"ModelName\":\"DH-390 2MP\",\"FwVer\":\"v1.0.0.34\",\"HwVer\":\"\",\"FriendlyName\":\"DH-390 2MP ENG031\",\"UpTime\":548}" }
}

This are my models :

struct Information: Codable {

    let ModelName : String?

}

struct GetInformation: Codable {

    let Info: [String: Information]?

}

struct WebSystemInfo: Codable {

    let SERVERWebSystemInfoGet: GetInformation?

}

This is the method :

func parseGetInfo(data: Data) {

    do {
        let info = try JSONDecoder().decode(WebSystemInfo.self, from: data)
        print(info)
    } catch let error{
        print(error)
    }
}

And this is the error that i get :

typeMismatch(Swift.Dictionary Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "SERVERWebSystemInfoGet", intValue: nil), CodingKeys(stringValue: "Info", intValue: nil)], debugDescription: "Expected to decode Dictionary but found a string/data instead.", underlyingError: nil))

Upvotes: 0

Views: 2662

Answers (3)

Fabian
Fabian

Reputation: 5358

You copied JSON which has escaped bits: with \”, which makes the info-dictionary a string.

Try the following string with the escaping removed whether you can decode it.

{
  "SERVERWebSystemInfoGet": {
    "Return Code": 0,
    "Return String": "No Error",
    "Info": {
        "IT": "IT109200310_0",
        "MAC": "00:40:7F:41:F8:81",
        "UUID": "uuid:858fba00-d3a0-11dd-a001-00407f41f881",
        "SN":"ENG031",
        "ModelNumber": "DH-390 2MP",
        "ModelName": "DH-390 2MP",
        "FwVer": "v1.0.0.34",
        "HwVer": "x",
        "FriendlyName": "DH-390 2MP ENG031",
        "UpTime": "548"
    }
  }
}

Then you can think about changing the server output if you can, or decoding info manually if you can’t by following this guide, it starts at Manual Encoding and Decoding with the important bits.

Upvotes: 1

Shehata Gamal
Shehata Gamal

Reputation: 100543

This

 "Info" : "{\"IT\":\"IT109200310_0\",\"MAC\":\"00:40:7F:41:F8:81\",\"UUID\":\"uuid:858fba00-d3a0-11dd-a001-00407f41f881\",\"SN\":\"ENG031\",\"ModelNumber\":\"DH-390 2MP\",\"ModelName\":\"DH-390 2MP\",\"FwVer\":\"v1.0.0.34\",\"HwVer\":\"\",\"FriendlyName\":\"DH-390 2MP ENG031\",\"UpTime\":548}" }

is a json string not a dictionary you need

let Info:String?

Upvotes: 3

Aris
Aris

Reputation: 1559

This happens because the Info value is actually a string and not a dictionary. Notice that it starts with quotes.

Change the model to return Dictionary instead of String.

Upvotes: 2

Related Questions