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

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

得到这个 API 回复:

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

我正在解码为:

class Campaign: Codable {

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

一切正常。 但是有了这个回应:

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

当解码成:

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

我收到以下错误:

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))

不确定为什么解码 User 会给我问题,而解码 Campaign 却不会。

正如我在评论中所说,我认为您在 JSON 结果中的 "slogan" 属性 中收到了一个纯字符串。而不是像你描述的那样的对象。

我在游乐场试过:

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

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

给我错误:

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

如果我在 JSON 中放置一个真实的对象(与您的示例相同),它会起作用。

您的第二个对象似乎无效JSON。

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

这对我来说很好解码。

错误说的很清楚

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

是一个字符串而不是预期的字典。

请检查JSON