Codable简单使用

news/2024/7/20 22:37:42 标签: ios, json

在Swift中,需要将Json数据转为实体时,一种简单的方式就是使用系统提供的JSONDecoder进行解码,这种方式需要实体类或结构体继承(实现)(java说法)一个类型别名(typealias)为Codable的东西。这个东西长这样:

/// A type that can convert itself into and out of an external representation.
///
/// `Codable` is a type alias for the `Encodable` and `Decodable` protocols.
/// When you use `Codable` as a type or a generic constraint, it matches
/// any type that conforms to both protocols.
public typealias Codable = Decodable & Encodable

简单使用

普通的类或结构体,直接继承Codable 就行了,可以不用做别的实现,要是属性中有引用别的类或结构体,需要这个属性也要继承Codable ,如下:

struct  NewsResponse :Codable {
    var code: Int
    var msg: String
    var result: ResultModel
    struct  ResultModel : Codable {
        var curpage: Int
        var allnum: Int
        var newslist: [ListModel]
        struct  ListModel : Codable {
            var id: String
            var ctime: String
            var title: String
            let description: String
            var source: String
            var picUrl: String
            var url: String
        }
    }
}

但是如果这个类或结构体的属性中有泛型的话,需要多做一些处理,不然会有编译时错误,如图:
在这里插入图片描述
需要多做一下处理:
在这里插入图片描述
也可以多做一些处理:

    init(code: Int?, data: T?, msg: String?) {
            self.code = code
            self.data = data
            self.msg = msg
    }

    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        code = try container.decode(Int.self, forKey: .code)
        data = try container.decode(T.self, forKey: .data)
        msg = try container.decode(String.self, forKey: .msg)
    }

    func encode(to encoder: Encoder) throws {
        var container = encoder.container(keyedBy: CodingKeys.self)
        try container.encode(code, forKey: .code)
        try container.encode(data, forKey: .data)
        try container.encode(msg, forKey: .msg)
    }

    private enum CodingKeys: String, CodingKey {
        case code
        case data
        case msg
    }

Json解析

然后就可以解析数据了:
在这里插入图片描述

do {
	let base = try JSONDecoder().decode(BaseBN<UserBN>.self, from: jsonData)
    let user=base.data
    if user != nil {
    	self.login(user: user!)
	}
    print(user as Any)
} catch {
  	print("Error decoding JSON: \(error)")
}

http://www.niftyadmin.cn/n/5324462.html

相关文章

AnyDoor任意门:零样本物体级图像定制化

文章目录 一、AnyDoor简介二、AnyDoor方法&#xff08;一&#xff09;ID特征提取&#xff08;二&#xff09;细节特征提取&#xff08;三&#xff09;特征注入&#xff08;四&#xff09;视频、图像动态采样 一、AnyDoor简介 “任意门”算法&#xff1a;可以将任意目标传送到指…

MATLAB R2023a安装教程

鼠标右击软件压缩包&#xff0c;选择“解压到MATLAB.R2023a”。 打开解压后的文件夹&#xff0c;鼠标右击“R2023a_Windows_iso”选择“装载”。 鼠标右击“setup.exe”选择“以管理员身份运行”。 点击“高级选项”选择“我有文件安装密钥”。 点击“是”&#xff0c;然后点击…

Python数据结构——字符串

目录 一、字符串的不变性 二、字符串的常见方法介绍 三、字符串对象的join()和split()方法 四、删除空白的Istrip()和rstrip()方法 一、字符串的不变性 1、属于不可变对象&#xff0c;不能通过索引操作来改变字符串对象本身 s I like Python s[7] p 要修改字符串&#…

zybo——嵌入式笔记

zynq——嵌入式学习笔记(GPIO之MIO控制LED) GPIO是一个外设&#xff0c;用来对器件的引脚作观测&#xff08;input&#xff09;以及控制&#xff08;output&#xff0c;通过MIO模块&#xff09;。 MIO(Multiuse I/O),将来自PS外设和静态存储器接口的访问多路复用到PS的引脚上。…

Transformer从菜鸟到新手(六)

引言 上篇文章介绍了如何在多GPU上分布式训练&#xff0c;本文介绍大模型常用的一种推理加速技术——KV缓存。 KV Cache KV缓存(KV Cache)是在大模型推理中常用的一种技巧。我们知道在推理阶段&#xff0c;Transformer也只能像RNN一样逐个进行预测&#xff0c;也称为自回归。…

Uncaught TypeError: Cannot set properties of null (setting ‘textContent‘)是什么原因

这个错误提示表示试图设置一个 null 值的 textContent 属性&#xff0c;这通常是因为在试图操作一个不存在的或者不存在于文档中的元素而导致的。 在使用 document.getElementById() 或者类似的方法获取元素时&#xff0c;如果参数所对应的元素不存在时&#xff0c;会返回 nul…

浅谈 Android焦点管理机制 事件分发机制

什么是焦点 焦点能够让 视图和窗口 可以接受和处理 按键事件和导航事件 。在 Android 中&#xff0c;按键事件和导航事件通常指的是 与物理按键和输入设备&#xff08;如键盘、遥控器、游戏手柄等&#xff09;相关的交互事件 。 焦点的处理对于非触摸屏设备&#xff08;如电视…

2022年面经记录(base杭州)

duandian科技&#xff08;笔试未通过&#xff09; 笔试题&#xff1a;leetCode热题第20题有效的括号 面后感&#xff1a;没怎么刷算法题&#xff0c;js 基础不扎实 laiweilai&#xff08;三面未通过&#xff09; 一面&#xff1a;笔试题 写一个函数&#xff0c;获取url中的指定…