text JSONEncoder对数据进行编码/解码

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了text JSONEncoder对数据进行编码/解码相关的知识,希望对你有一定的参考价值。


extension JSONEncoder {
    func encodeJSONObject<T: Encodable>(_ value: T, options opt: JSONSerialization.ReadingOptions = []) throws -> Any {
        let data = try encode(value)
        return try JSONSerialization.jsonObject(with: data, options: opt)
    }
}

extension JSONDecoder {
    func decode<T: Decodable>(_ type: T.Type, withJSONObject object: Any, options opt: JSONSerialization.WritingOptions = []) throws -> T {
        let data = try JSONSerialization.data(withJSONObject: object, options: opt)
        return try decode(T.self, from: data)
    }
}

以上是关于text JSONEncoder对数据进行编码/解码的主要内容,如果未能解决你的问题,请参考以下文章