JSONDecoder 无法解码 Array 但可以解码 String

JSONDecoder can't decode Array but can decode String

我想从 Json:

解析一个结构
struct Subsidiary: Decodable {
    let id: Int?
    let subsidiary_ref: String?
    let name: String?
    let address: String?
}

我试着像这样解析它:

let sub: [Subsidiary] = try! JSONDecoder().decode([Subsidiary].self, from: data)

其中数据是来自

的数据类型
session.dataTask(with: urlRequest) { (data, response, error) in

它给了我一个错误

Fatal error: 'try!' expression unexpectedly raised an error: Swift.DecodingError.typeMismatch(Swift.Array<Any>, Swift.DecodingError.Context(codingPath: [], debugDescription: "Expected to decode Array<Any> but found a string/data instead.", underlyingError: nil))

如果我这样做:

let sub: String = try! JSONDecoder().decode(String.self, from: data)

它有效,它给了我儿子

[
   {"id": 5913, "subsidiary_ref": "0000159", "name": "Mercator Hipermarket Koper", "address": "Poslov.98-Koper,Dolinska C", "city": "Koper", "coordinates_x": null, "coordinates_y": null, "phone_number": "+386 56-636-800", "frequency": "A", "channel": "Food", "subchannel": "Hypermarket", "customer": 7, "day_planned": true, "badge_visible": true, "open_call": true, "number_of_planned": 13, "number_of_calls": 22, "last_call_day": 3, "notes": " notesi ki ne smejo nikoli zginiti bla marko bdsa"},
    {"id": 5870, "subsidiary_ref": "0000773", "name": "Kompas Shop Pe Ferneti?i", "address": "Partizanska 150", "city": "Se?ana", "coordinates_x": null, "coordinates_y": null, "phone_number": "+386 57-380-636", "frequency": "A", "channel": "Food", "subchannel": "Supermarket", "customer": 17, "day_planned": true, "badge_visible": true, "open_call": true, "number_of_planned": 13, "number_of_calls": 1, "last_call_day": 1, "notes": null},...
]

我的代码有什么问题?

编辑:

我发现,如果我创建一个 string 变量,然后将此字符串值转换为数据,它甚至可以与 Subsidiary 结构一起使用。

所以 data 变量应该有问题。

您可以解码 String.self 并打印 JSON 这一事实意味着 JSON 的根是一个字符串。你得到的JSON,以文本形式,大概是这样的:

"[\r\n   {\"id\": 5913, \"subsidiary_ref\": \"0000159\", \"name\": \"Mercator Hipermarket Koper\", \"address\": \"Poslov.98-Koper,Dolinska C\", \"city\": \"Koper\", \"coordinates_x\": null, \"coordinates_y\": null, \"phone_number\": \"+386 56-636-800\", \"frequency\": \"A\", \"channel\": \"Food\", \"subchannel\": \"Hypermarket\", \"customer\": 7, \"day_planned\": true, \"badge_visible\": true, \"open_call\": true, \"number_of_planned\": 13, \"number_of_calls\": 22, \"last_call_day\": 3, \"notes\": \" notesi ki ne smejo nikoli zginiti bla marko bdsa\"}\r\n]"

请注意,您想要的实际 JSON 放在 "" 中,因此所有特殊字符都被转义了。

Web 服务以一种非常奇怪的方式提供了 JSON...

要解码实际的JSON数据,需要先获取字符串,然后将字符串转为Data,然后再次解码Data

// nil handling omitted for brevity
let jsonString = try! JSONDecoder().decode(String.self, from: data)
let jsonData = jsonString.data(using: .utf8)!
let sub = try! JSONDecoder().decode([Subsidiary].self, from: jsonData)

当然,最好的解决办法是修复后端。