gpt4 book ai didi

json - 如何在 Swift 4 中正确解析带有根元素的 JSON 作为数组?

转载 作者:行者123 更新时间:2023-12-02 03:41:08 29 4
gpt4 key购买 nike

我从 API 得到以下响应:

[
{
"stores": [
{
"store": {
"Name": "A store name",
"City": "NY"
}
},
{
"store": {
"Name": "A second store name",
"City": "ny2"
}
}
]
},

{

"products": [
{
"product": {
"name": "a product",
"price": "1"
}
},
{
"product": {
"name": "a second product",
"price": "2"
}
}
]

}

]

对于两个 JSON 对象(商店和产品),我创建了以下结构:

struct shops_response: Codable {

var stores: [stores]
}

struct products_response: Codable {

var products: [products]
}


struct stores: Codable {
var store: store
}

struct store: Codable {
var Name:String
var City:String
}

struct products: Codable {
var product: product
}

struct product: Codable {

var name:String
var price:String

}

使用下面的代码我已经成功解析了响应(其中 APIresponse.json 是从 API 接收到的 json - 我将它仅用于测试目的):

let path = Bundle.main.path(forResource: "APIresponse", ofType: "json")
let url = URL(fileURLWithPath: path!)

let data = try! Data(contentsOf:url)

let jsonArray = try! JSONSerialization.jsonObject(with: data, options: []) as? [[String:Any]]
let storesJsonData = try! JSONSerialization.data(withJSONObject: jsonArray![0], options: .prettyPrinted)
let productsJsonData = try! JSONSerialization.data(withJSONObject: jsonArray![1], options: .prettyPrinted)


let stores = try! JSONDecoder().decode(shops_response.self, from: storesJsonData)
let products = try! JSONDecoder().decode(products_response.self, from: productsJsonData)

我的问题是:在 Swift 4 中是否有另一种更清晰/更简单的方法来解析这种类型的 json?

最佳答案

这确实是一个结构笨拙的 JSON。如果您无法让发件人更改格式,这是我尝试使用 JSONDecoder 对其进行解析的尝试:

typealias Response = [Entry]

struct Entry: Codable {
let stores: [StoreEntry]?
let products: [ProductEntry]?
}

struct ProductEntry: Codable {
let product: Product
}

struct Product: Codable {
let name, price: String
}

struct StoreEntry: Codable {
let store: Store
}

struct Store: Codable {
let name, city: String

enum CodingKeys: String, CodingKey {
case name = "Name"
case city = "City"
}
}

let response = try JSONDecoder().decode(Response.self, from: data)
let stores = response.flatMap { $0.stores.map { $0.map { $0.store } } }.flatMap { $0 }
let products = response.flatMap { $0.products.map { $0.map { $0.product } } }.flatMap { $0 }

关于json - 如何在 Swift 4 中正确解析带有根元素的 JSON 作为数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48596376/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com