gpt4 book ai didi

json - map 字典 [字符串 :Any] to class

转载 作者:搜寻专家 更新时间:2023-11-01 06:01:20 25 4
gpt4 key购买 nike

我想知道是否有办法将字典映射到类。如果这是我的课:

class Class{
var x = 0
var y = "hi"
}

这是我的字典 (dict),类型为 [String: Any]

["x": 1, "y": "hello"]

有什么简单的方法可以将字典的值转换为我的类Class吗?

我现在这样做:

classInstance.x = dict["x"] as? Int ?? 0

我想知道是否可以在 JSON 中搜索与类变量名称匹配的键,如果匹配,则将 JSON 键的值分配给类变量的值.以我的方式(如上),我需要逐行输入它,也许有一行代码可以将 JSON 映射到类中。

最佳答案

带有 JSONSerializationCodable 的内置解决方案

let dictionary : [String:Any] = ["x": 1, "y": "hello"]

class Class : Codable {
let x : Int
let y : String
}

do {
let jsonData = try JSONSerialization.data(withJSONObject: dictionary)
let instance = try JSONDecoder().decode(Class.self, from: jsonData)
print(instance.x, instance.y)
} catch {
print(error)
}

关于json - map 字典 [字符串 :Any] to class,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49338266/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com