【发布时间】:2020-04-24 16:07:33
【问题描述】:
我有一个我想从 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 变量应该有问题。
【问题讨论】:
-
你能做到吗
print(String(data: data, enoding: .utf8))我认为你已经将 JSON 字符串化了,以双引号开头并以它们结尾。
标签: ios json swift decodable jsondecoder