解码错误:typeMismatch-预期对Dictionary进行解码 但找到了字符串/数据

问题描述 投票:0回答:3

获得此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))

不确定解码用户为什么不解码广告给我带来了问题。

获得此API响应:...“ campaigns”:[{“ id”:2,“ name”:{“ en”:“ Example Campaign”,“ de”:“ Beispiel Kampagne” ...

swift codable
3个回答
1
投票

您的第二个对象似乎不是有效的JSON。

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

0
投票

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


0
投票

错误清楚地表明

© www.soinside.com 2019 - 2024. All rights reserved.