使用Decodable(嵌套数组)解析不同的JSON

时间:2017-11-28 23:39:29

标签: json swift4 decodable

我正在使用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?
}

响应等于零,我无法理解我做错了什么,我理解问题是解析工作数组,因为如果我评论工作者响应等于一些有效数据。 谢谢你的帮助!

1 个答案:

答案 0 :(得分:1)

由于错误的逗号,您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)