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 = getValue<Product>(from: myJson, field: "product")
let employee = getValue<Employee>(from: myJson, field: "employee")
这可能是 JSONDecoder
或者我应该使用 JSONSerialization
,首先读出给定json的"subtree"然后将其传递给解码器?在swift中似乎不允许在泛型函数中定义结构 .
2 回答
Decodable
假设您在设计时知道您想要的所有内容以启用静态类型 . 您想要的动态越多,您就越有创意 . 在这种情况下,定义通用编码键结构非常方便:我建议使用Code Different's answer,但是如果你寻求一种不同的方式,那么在表面下以相同的方式工作,我已经扩展了他们的解决方案,导致下面的代码 .
我也会推荐这些:
How to use Any in Codable Type
Swift 4 Codable; How to decode object with single root-level key