如何在 Swift 4 中使用根元素作为数组正确解析 JSON?

Mad*_*lin 1 json swift4

我从 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"
                }
            }
        ]

    }

]
Run Code Online (Sandbox Code Playgroud)

对于两个 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

}
Run Code Online (Sandbox Code Playgroud)

使用下面的代码,我成功解析了响应(其中 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)
Run Code Online (Sandbox Code Playgroud)

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

Ger*_*eon 5

这确实是一个结构笨拙的 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 }
Run Code Online (Sandbox Code Playgroud)