在Swift中动态解码任意json字段

在Swift中动态解码任意json字段,第1张

概述TL; DR 有没有办法可以使用JSONDecoder并编写一个函数,它只是从给定的json读出指定的可解码类型的字段值? 成像我有以下json: { "product":{ "name":"PR1", "price":20 }, "employee":{ "lastName":"Smith", "department":"IT", TL; DR

有没有办法可以使用JSONDecoder并编写一个函数,它只是从给定的Json读出指定的可解码类型的字段值?

成像我有以下Json:

{   "product":{      "name":"PR1","price":20   },"employee":{      "lastname":"Smith","department":"IT","manager":"Anderson"   }}

我有2个可解码结构:

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中似乎不允许在泛型函数中定义结构.

解决方法 可解码假定您在设计时知道所需的一切以启用静态类型.你想要的动态越多,你就越有创意.在这种情况下,定义通用编码键结构非常方便:

/// A structure that holds no fixed key but can generate dynamic keys at run timestruct GenericCodingKeys: CodingKey {    var stringValue: String    var intValue: Int?    init?(stringValue: String) { self.stringValue = stringValue }    init?(intValue: Int) { self.intValue = intValue; self.stringValue = "\(intValue)" }    static func makeKey(_ stringValue: String) -> GenericCodingKeys { return self.init(stringValue: stringValue)! }    static func makeKey(_ intValue: Int) -> GenericCodingKeys { return self.init(intValue: intValue)! }}/// A structure that retains just the decoder object so we can decode dynamically laterfileprivate struct JsONHelper: Decodable {    let decoder: Decoder    init(from decoder: Decoder) throws {        self.decoder = decoder    }}func getValue<T: Decodable>(from Json: Data,fIEld: String) throws -> T {    let helper = try JsONDecoder().decode(JsONHelper.self,from: Json)    let container = try helper.decoder.container(keyedBy: GenericCodingKeys.self)    return try container.decode(T.self,forKey: .makeKey(fIEld))}let product: Product = try getValue(from: Json,fIEld: "product")let employee: Employee = try getValue(from: Json,fIEld: "employee")
总结

以上是内存溢出为你收集整理的在Swift中动态解码任意json字段全部内容,希望文章能够帮你解决在Swift中动态解码任意json字段所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/web/1007757.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-22
下一篇 2022-05-22

发表评论

登录后才能评论

评论列表(0条)

保存