我正在使用NiceHash API的应用程序。我必须与这样的JSON合作:
{
"result":{
"addr":"37ezr3FDDbPXWrCSKNfWzcxXZnc7qHiasj",
"workers":[
[ "worker1", { "a":"45.7" }, 9, 1, "32", 0, 14 ],
[ "worker1", { }, 5, 1, "100000", 0, 22 ],
]
"algo":-1
},
"method":"stats.provider.workers"
}
用于解析这样的结构
struct Root: Decodable {
var result: WorkersResult?
var method: String?
}
struct WorkersResult: Decodable {
var addr: String?
var workers: [Workers]?
var algo: Int?
}
struct Workers: Decodable {
var worker: [Worker]?
}
struct Worker: Decodable {
var name: String?
var hashrate: Hashrate?
var time: Int?
var XNSUB: Int?
var difficult: String?
var reject: Int?
var algo: Int?
}
struct Hashrate: Decodable {
var rate: String?
}
响应是相等的,我不明白我在做错了什么,我知道问题是解析工人的阵列,因为如果我对工人评论响应等于某些有效的数据。感谢您的帮助!
您的JSON实际上由于逗号放错了。通过JSON验证器运行到现在的意思。
无论如何,由于Worker
(单数)被编码为数组,因此您需要为其提供自定义解码器。Workers
(复数)是不必要的。
struct Root: Decodable {
var result: WorkersResult?
var method: String?
}
struct WorkersResult: Decodable {
var addr: String?
var workers: [Worker]?
var algo: Int?
}
struct Worker: Decodable {
var name: String?
var hashrate: Hashrate?
var time: Int?
var XNSUB: Int?
var difficult: String?
var reject: Int?
var algo: Int?
init(from decoder: Decoder) throws {
var container = try decoder.unkeyedContainer()
name = try container.decodeIfPresent(String.self)
hashrate = try container.decodeIfPresent(Hashrate.self)
time = try container.decodeIfPresent(Int.self)
XNSUB = try container.decodeIfPresent(Int.self)
difficult = try container.decodeIfPresent(String.self)
reject = try container.decodeIfPresent(Int.self)
algo = try container.decodeIfPresent(Int.self)
}
}
struct Hashrate: Decodable {
var rate: String?
private enum CodingKeys: String, CodingKey {
case rate = "a"
}
}
用法:
let jsonData = """
{
"result":{
"addr":"37ezr3FDDbPXWrCSKNfWzcxXZnc7qHiasj",
"workers":[
[ "worker1", { "a":"45.7" }, 9, 1, "32", 0, 14 ],
[ "worker1", { }, 5, 1, "100000", 0, 22 ]
],
"algo":-1
},
"method":"stats.provider.workers"
}
""".data(using: .utf8)!
let r = try JSONDecoder().decode(Root.self, from: jsonData)
print(r)