【发布时间】:2018-12-09 22:19:36
【问题描述】:
TL;DR
有没有一种方法可以让我使用JSONDecoder 并编写一个函数,该函数将从给定的 json 给定的指定可解码类型的字段值中读出?
成像我有以下json:
{
"product":{
"name":"PR1",
"price":20
},
"employee":{
"lastName":"Smith",
"department":"IT",
"manager":"Anderson"
}
}
我有 2 个Decodable 结构:
struct Product: Decodable {
var name: String
var price: Int
}
struct Employee: Decodable {
var lastName: String
var department: String
var manager: String
}
我想写一个函数
func getValue<T:Decodable>(from json: Data, field: String) -> T { ... }
所以我可以这样称呼它:
let product: Product = getValue(from: myJson, field: "product")
let employee: Employee = getValue(from: myJson, field: "employee")
这可能与JSONDecoder 或我应该与JSONSerialization 混淆,首先读出给定json 的“子树”,然后将其传递给解码器? swift 中似乎不允许在泛型函数中定义结构。
【问题讨论】:
标签: json swift nsjsonserialization jsondecoder