使用例子代码:
1.服务器返回的json:
let json = """
{"userInfos": [{"age": 18,"sex": true,"height": 178.55999,"userName": "小黑"},{"age": 20,"sex": false,"height": 150.555,"userName": "小百"}]}
"""
2.创建的模型类
①. 非修改结构中的key值
struct UserList: Codable {
var userInfos: [UserInfo] = []
struct UserInfo: Codable {
var userName: String = ""
var age: Int?
var height: Float?
var sex: Bool = false
}
}
②. 修改结构中某个key值(自定义键值名)
struct UserList: Codable {
var userInfos: [UserInfo] = []
struct UserInfo: Codable {
var userName: String = ""
var age: Int?
var bodyHeight: Float? // key: height
var sex: Bool = false
// 改变key的名称; 需要全部都在枚举中体现(不用修改key的, 也需写出) 写出的key与结构中顺序无关
private enum CodingKeys: String, CodingKey {
case bodyHeight = "height"
case userName
case age
case sex
}
}
}
- 使用
let data = json.data(using: .utf8)!
let jsonDecoder = JSONDecoder()
let model = try? jsonDecoder.decode(UserList.self, from: data)
附上 模型->json:
let encoder = JSONEncoder()
encoder.outputFormatting = .prettyPrinted //输出的格式设置
let data1 = try? encoder.encode(model)
网友评论