使用 Swift 4 的Encoder
&Decoder
协议以及JSONDecoder
如何Codeable
使用给定 JSON 中的键初始化类型结构。
即给定下面的JSON,我希望只用于results
初始化Example
{
"boolean": true,
"number": 123,
"results": {
"a": "b",
"c": "d",
"e": "f"
},
"string": "Hello World"
}
struct Example: MDB, Codeable{
var a: String
var b: String
var c: String
}
public static func initalize<T: Codable & MDBItem>(json: Data) -> [T]{
var items = [T]()
let decoder = JSONDecoder()
do {
//How do I initialize `T` using a key from the JSON given
//ie. decoder.decode([T].self, from: json["results"])
// Or decoder.decode(["results", [T].self, from: json)
items = try decoder.decode([T].self, from: json)
} catch {
print("error trying to convert data to JSON")
}
return items
}