作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我从 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/
我是一名优秀的程序员,十分优秀!