【问题标题】:JSONDecoder - "Expected to decode Dictionary<String, Any> but found a string/data instead."JSONDecoder - “预期解码 Dictionary<String, Any> 但找到了一个字符串/数据。”
【发布时间】:2018-08-27 11:45:37
【问题描述】:

所以我试图解码一个 json 并得到这个错误。

这是 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}" }
}

这是我的模型:

struct Information: Codable {

    let ModelName : String?

}

struct GetInformation: Codable {

    let Info: [String: Information]?

}

struct WebSystemInfo: Codable {

    let SERVERWebSystemInfoGet: GetInformation?

}

这是方法:

func parseGetInfo(data: Data) {

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

这是我得到的错误:

typeMismatch(Swift.Dictionary Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "SERVERWebSystemInfoGet", intValue: nil), CodingKeys(stringValue: "Info", intValue: nil)], debugDescription: "期望解码 Dictionary 但找到了一个字符串/数据。",底层错误: nil))

【问题讨论】:

  • 请学会理解解码错误信息,它们非常具有描述性。错误表示您要解码字典,但实际对象是字符串 (Info)。

标签: ios swift decode jsondecoder


【解决方案1】:

这个

 "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}" }

是一个json字符串而不是你需要的字典

let Info:String?

【讨论】:

【解决方案2】:

这是因为Info 值实际上是一个字符串而不是字典。 请注意,它以引号开头。

更改模型以返回 Dictionary 而不是 String。

【讨论】:

    【解决方案3】:

    您复制了带有转义位的 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": "x",
            "FriendlyName": "DH-390 2MP ENG031",
            "UpTime": "548"
        }
      }
    }
    

    然后您可以考虑更改服务器输出,或者如果您不能按照this guide 手动解码info,它从手动编码和解码开始,重要的是位。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-04-11
      • 2020-12-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多