使用 Swift 4 的 Encoder
和 Decoder
协议(protocol)和 JSONDecoder
如何使用初始化 Codeable
类型的结构体来自给定 JSON 的 key 。
即鉴于下面的 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
}
最佳答案
一个可能的简单方法是创建一个包装器结构。
所以,你有这个 JSON
let json = """
{
"boolean": true,
"number": 123,
"results": {
"a": "b",
"c": "d",
"e": "f"
},
"string": "Hello World"
}
"""
由于您只对定义此结构的“结果”
部分感兴趣
struct Example: Codable {
let a: String
let c: String
let e: String
}
包装器
现在,为了利用 Codable
协议(protocol)(在 Swift 4 中提供)的强大功能,您可以创建一个像这样的包装器结构
struct Wrapper: Codable {
let results: Example
}
The only purpose of the Wrapper struct is to define a path from the root of the original JSON to the section you are interested in. This was the
Codable
protocol will do the rest of the job for you.
解码
现在您可以使用 Wrapper 结构轻松解码 JSON。
if
let data = json.data(using: .utf8),
let wrapper = try? JSONDecoder().decode(Wrapper.self, from: data) {
let results = wrapper.results
print(results)
}
最后,您可以从包装器中提取 results
属性。
关于ios - 使用 JSON swift4 中的 key 解码结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44731991/