Swift   发布时间:2022-04-30  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了在Swift中动态解码任意json字段大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
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 { ... }

@R_788_9447@这样称呼它:

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 time
struct 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 later
fileprivate 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字段所遇到的程序开发问题。

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

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。