我为练习创建了一个非常简单的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.*`
答案 0 :(得分:3)
您的JSON
替换
let js = "[{\"a\":\"1\",\"b\":\"2\"},{\"c\":\"3\",\"d\":\"4\"}]"
与
let js = "[{\"a\":\"1\",\"b\":\"2\"},{\"a\":\"3\",\"b\":\"4\"}]"
其他词典没有键a
和b
,这就是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
}
}