获取和解析JSON



我很难获取和解析以下JSON。我甚至无法从给定的url中获取数据,更不用说使用我的数据模型来解析它了;汽车";。欢迎任何帮助!

JSON-

{
"cars":[
{
"date_stolen":1604616183,
"description":null,
"body_colors":[
"Black",
"Blue"
],
"id":"944846",
"is_stock_img":false,
"large_img":null,
"location_found":null,
"manufacturer_name":"Toyota",
"external_id":null,
"registry_name":null,
"registry_url":null,
"serial":"36-17-01012-xl09",
"status":null,
"stolen":true,
"stolen_location":"Calgary - CA",
"thumb":null,
"title":"2017 Toyota Corolla ",
"url":"https://cars.org/944846",
"year":2017
}
]
}
struct Car: Decodable {
let cars: String
}
var cars = [Car]()
fileprivate func fetchJSON() {
let urlString = "someUrl…"
guard let url = URL(string: urlString) else { return }
URLSession.shared.dataTask(with: url) { (data, _, err) in
DispatchQueue.main.async {
if let err = err {
print("Failed to get data from url:", err)
return
}

guard let data = data else { return }

do {

let decoder = JSONDecoder()

decoder.keyDecodingStrategy = .convertFromSnakeCase
print("DATA n", data)
self.cars = try decoder.decode(Car.self, from: data)

print("---> ", data)

} catch let jsonErr {
print("Failed to decode:", jsonErr)
}
}
}.resume()
}

You-Car模型并不代表您的json结构。

你正在寻找这样的东西:

struct CarsResponse: Decodable {
let cars: [CarDTO]
}
struct CarDTO: Decodable {
let id: String
let isStockImg: Bool
// And so on
}

然后只需写:

let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
let carResponse = try decoder.decode(CarsResponse.self, from: data)

您将通过编写来访问您的汽车

let cars: [CarDTO] = carResponse.cars

如果要使用可编码协议和JSONDecoder(),则需要创建一个与JSON格式匹配的Struct。正如其他人在评论中指出的那样,你的Car结构与你收到的数据格式完全不同。

如果您只想将接收到的JSON反序列化为包含值的字典,则可以使用JSONSerialization。

要做到这一点,您可以将do块的主体替换为以下代码:

let object = try JSONSerialization.jsonObject(with: data, options: []) 

然后,您必须自己浏览object的字典结构。它不像创建自定义结构和使用Codable那样干净,但它是有效的。

请注意,JSON中有语法错误

{"cars":
[
{"date_stolen":1604616183,
"description":null,
"body_colors":["Black","Blue"],
"id":944846,
"is_stock_img":false,
"large_img":null,
"location_found":null,
"manufacturer_name":"Toyota",
"external_id":null,
"registry_name":null,
"registry_url":null,
"serial":"36-17-01012-xl09",
"status":null,
"stolen":true,
"stolen_location":"Calgary - CA",
"thumb":null,
"title":"2017 Toyota Corolla ",
"url":"https://cars.org/944846",
"year":2017
}
]
}

(为了可读性,我添加了空白。它不会以任何方式影响解析。(

相关内容

  • 没有找到相关文章

最新更新