我刚刚学习了 Argo 基础知识,并且能够在生产环境中解码 99% 的 JSON。现在我面临以下结构(“5447”和“5954”等键是动态的)并且需要帮助:
{
"5447": {
"business_id": 5447,
"rating": 5,
"comment": "abcd",
"replies_count": 0,
"message_id": 2517
},
"5954": {
"business_id": 5954,
"rating": 3,
"comment": "efgh",
"replies_count": 0,
"message_id": 633
}
}
Argo解码的典型示例如下:
struct User {
let id: Int
let name: String
}
对于 JSON 结构(键是固定的“id”和“name”):
{
"id": 124,
"name": "someone"
}
使用这样的东西:
extension User: Decodable {
static func decode(j: JSON) -> Decoded<User> {
return curry(User.init)
<^> j <| "id"
<*> j <| "name"
}
}
但是我需要解析的数据结构不适合这个例子。
更新:使用 Tony 的第一个实现并在最后一行稍作修改,我完成了我的工作。这是完整的工作代码:
业务.swift:
import Argo
import Curry
import Runes
struct Business {
let businessID: Int
let rating: Double?
let comment: String?
let repliesCount: Int?
let messageID: Int?
}
extension Business: Decodable {
static func decode(_ json: JSON) -> Decoded<Business> {
let c0 = curry(Business.init)
<^> json <| "business_id"
<*> json <|? "rating"
return c0
<*> json <|? "comment"
<*> json <|? "replies_count"
<*> json <|? "message_id"
}
}
企业.swift
import Argo
import Runes
struct Businesses {
let businesses: [Business]
}
extension Businesses: Decodable {
static func decode(_ json: JSON) -> Decoded<Businesses> {
let dict = [String: JSON].decode(json)
let arr = dict.map { Array($0.map { $1 }) }
let jsonArr = arr.map { JSON.array($0) }
return Businesses.init <^> jsonArr.map([Business].decode).value ?? .success([])
}
}