本文介绍: 使用Codable进行模型字典模型数组字典数组的互转都是需要对象转成。找不到value,当这个Value声明时候没有定义成可选。找不到Key,当这个Key声明时候没有定义成可选。这样就可以避免名称冲突。,那么Json中不包含这个。以上代码是将Json中。,那么如果value为。

代码

import Foundation

struct YZWJsonExtension {
    //MARK: - decode
    /// 解码入口。type传入AnyClass.self
    public static func decode<T>(type: T.Type, object: Any?) throws -> T? where T : Decodable {
        if let object = object, let data = YZWJsonExtension.decode(object: object) {
            return YZWJsonExtension.decode(type: type, data: data)
        }
        return nil
    }
    
    /// 将object转成data
    public static func decode(object: Any) -> Data? {
        if let data = object as? Data {
            return data
        } else if let string = object as? String {
            return string.data(using: .utf8)
        }
        return try? JSONSerialization.data(withJSONObject: object)
    }
    
    /// codable
    private static func decode<T>(type: T.Type, data: Data) -> T? where T : Decodable {
        do {
            let object = try JSONDecoder().decode(type, from: data)
            return object
        } catch {
            
            if let jsonStr = String(data: data, encoding: .utf8) {
                print(jsonStr)
            }
            
            switch error {
            case let DecodingError.typeMismatch(_, context):
                print("数据类型错误:", context.codingPath, context.debugDescription, separator: "nn", terminator: "n")
            case let DecodingError.valueNotFound(_, context):
                print("找不到value:", context, separator: "n", terminator: "nn")
            case let DecodingError.keyNotFound(_, context):
                print("找不到Key:", context, separator: "n", terminator: "nn")
            case let DecodingError.dataCorrupted(context):
                print("Json格式错误:", context, separator: "n", terminator: "nn")
            default:
                print("Decode出现未知异常")
            }
        }
        return nil
    }
    
    //MARK: - encode 编码
    /// model, models -> type类型
    public static func encodeJsonObject<T>(model: T) -> Any? where T : Encodable {
        if let data = try? JSONEncoder().encode(model) {
            return try? JSONSerialization.jsonObject(with: data)
        }
        return nil
    }
    
    /// model, models转成json data
    public static func encodeData<T>(model: T) -> Data? where T: Encodable {
        return try? JSONEncoder().encode(model)
    }
}

使用Codable必要条件

使用Codable需要满足

  1. 对象structclass类型,并继承Codable对象
  2. 如果存储属性enumstructclass类型,也必须继承Codable对象

转换原理

使用Codable进行模型字典模型数组字典数组的互转都是需要对象转成Data类型通过Data类型来进行转换

Data是一串Json(NSJSONWritingPrettyPrinted)格式字符串使用UTF8编码转成的Data

JsonString to Data

jsonString.data(using: .utf8)

Array or Dictionary to Data

JSONSerialization.data(withJSONObject: object)

Array or Model to Data

JSONEncoder().encode(model) // model 为Array<Model>或Model

Data to JsonString

String(data: data, encoding: .utf8)

Data to Array or Dictionary

JSONSerialization.jsonObject(with: data)

Data to Array or Model

JSONDecoder().decode([Model].self, from: data) // Array<Model> , [Model] 也可以写成 Array<Model>
JSONDecoder().decode(Model.self, from: data) // Model

CodingKeys(Json的key语言声明冲突

enum CodingKeys: String, CodingKey {
	case yourKey = "jsonKey"
}

以上代码是将Json中jsonKey这个名称替换yourKey。这样就可以避免名称冲突
只需将需要替换的Key进行设置,如果没有存在需要修改的Key,那么这个enum可以不写

报错

DecodingError.typeMismatch(_, context)

数据类型错误

DecodingError.valueNotFound(_, context)

找不到value,当这个Value声明时候没有定义成可选?,那么如果value空值则会报这个错。

DecodingError.keyNotFound(_, context)

找不到Key,当这个Key在声明的时候没有定义成可选?,那么Json中不包含这个Key则会报这个错。

DecodingError.dataCorrupted(context)

Json格式错误

原文地址:https://blog.csdn.net/Yzzzzw01/article/details/131597095

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任

如若转载,请注明出处:http://www.7code.cn/show_45314.html

如若内容造成侵权/违法违规/事实不符,请联系代码007邮箱suwngjj01@126.com进行投诉反馈,一经查实,立即删除

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注