-1

我正在开发来自 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?
}

响应等于 nil,我不明白我做错了什么,我知道问题在于解析工人数组,因为如果我评论工人,响应等于一些有效数据。感谢帮助!

4

1 回答 1

1

由于逗号放错了,您的 JSON 实际上是无效的。通过 JSON 验证器运行它到现在我的意思。

无论如何,由于Worker(singular) 被编码为数组,因此您需要为其提供自定义解码器。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)
于 2017-11-29T02:56:54.220 回答