如何在swift4中为此json数据创建结构?

时间:2019-01-03 09:31:25

标签: swift

我为练习创建了一个非常简单的json数据,但是当JSONDecoder()。decode时,它总是解码错误。我尝试通过某种方式修改我的结构,但是所有错误都相同(打印“ error0”)。代码在下面。

gulp.src(sourceFiles)
    .pipe(munge()) // I don't know what to do here!!
    .pipe(del());  // does a `del ./js/dist/hoobly.*`
                   // and a  `del ./js/dist/hoo.*`

2 个答案:

答案 0 :(得分:3)

您的JSON替换

出现问题
let js = "[{\"a\":\"1\",\"b\":\"2\"},{\"c\":\"3\",\"d\":\"4\"}]"

let js = "[{\"a\":\"1\",\"b\":\"2\"},{\"a\":\"3\",\"b\":\"4\"}]"

其他词典没有键ab,这就是JSONDecoder无法decode的原因,现在您的更新代码将是:

struct ss : Codable {
    var a : String
    var b : String
}


let js = "[{\"a\":\"1\",\"b\":\"2\"},{\"a\":\"3\",\"b\":\"4\"}]"
let data = js.data(using: .utf8)

let a = [ss].self

do {
    let jsonDecoder = JSONDecoder()
    let s = try jsonDecoder.decode(a, from: data!)
    print(s[0].a) //"1\n"
} catch {
    print(error)
}

PS:如@Milander所建议,如果您不想修复JSON,则可以在optional中设置Struct属性,如

struct ss : Codable {
    let a, b, c, d: String?
}

答案 1 :(得分:0)

您可以如下定义其他键:

No optional No replacement

struct ss : Codable {
    var a : String
    var b : String

    init(from decoder: Decoder) throws {
        if let con = try? decoder.container(keyedBy: CodingKeys.self), let a = try? con.decode(String.self, forKey: .a), let b = try? con.decode(String.self, forKey: .b) {
            self.a = a
            self.b = b
        } else if let con = try? decoder.container(keyedBy: AdditionalInfoKeys.self), let c = try? con.decode(String.self, forKey: .c), let d = try? con.decode(String.self, forKey: .d) {
            a = c
            b = d
        } else {
            throw NSError(domain: "Decoding error", code: 123, userInfo: nil)
        }
    }

    enum AdditionalInfoKeys: String, CodingKey {
        case c, d
    }
}