class 序列化和反序列化json
import serialization.serialization.* import std.math.* import encoding.json.* /* 通过实现 Serializable 接口,来实现对自定义类型的序列化和反序列化功能 */ class Abc <: Serializable<Abc> { var name: String = "Abcde" var age: Int64 = 555 var loc: Option<Location> = Option<Location>.None /* 实现 Serializable 接口的序列化方法 */ public func serialize(): DataModel { return DataModelStruct().add(field<String>("name", name)).add(field<Int64>("age", age)).add(field<Option<Location>>("loc", loc)) } /* 实现反序列化方法 */ public static func deserialize(dm: DataModel): Abc { let dms = match (dm) { case data: DataModelStruct => data case _ => throw Exception("this data is not DataModelStruct") } let result = Abc() result.name = String.deserialize(dms.get("name")) result.age = Int64.deserialize(dms.get("age")) result.loc = Option<Location>.deserialize(dms.get("loc")) return result } } class Location <: Serializable<Location> { var time: Int64 = 666 var heheh: Rune = 'T' /* 实现 Serializable 接口的序列化方法 */ public func serialize(): DataModel { return DataModelStruct().add(field<Int64>("time", time)).add(field<Rune>("heheh", heheh)) } /* 实现反序列化方法 */ public static func deserialize(dm: DataModel): Location { let dms = match (dm) { case data: DataModelStruct => data case _ => throw Exception("this data is not DataModelStruct") } let result = Location() result.time = Int64.deserialize(dms.get("time")) result.heheh = Rune.deserialize(dms.get("heheh")) return result } } main(): Unit { let dd = Abc() let aa: JsonValue = dd.serialize().toJson() let bb: JsonObject = (aa as JsonObject).getOrThrow() let v1 = (bb.get("name").getOrThrow() as JsonString).getOrThrow() let v2 = (bb.get("age").getOrThrow() as JsonInt).getOrThrow() let v3 = bb.get("loc").getOrThrow() println(v1.getValue()) println(v2.getValue()) println(v3.toString()) println("===========") let aaa = ##"{"age": 123, "loc": { "heheh": "H", "time": 45 }, "name": "zhangsan"}"## let bbb = JsonValue.fromStr(aaa) let ccc = (bbb as JsonObject).getOrThrow() let v4 = (ccc.get("name").getOrThrow() as JsonString).getOrThrow() let v5 = (ccc.get("age").getOrThrow() as JsonInt).getOrThrow() let v6 = (ccc.get("loc").getOrThrow() as JsonObject).getOrThrow() let v7 = (v6.get("time").getOrThrow() as JsonInt).getOrThrow() let v8 = (v6.get("heheh").getOrThrow() as JsonString).getOrThrow() println(v4.getValue()) println(v5.getValue()) println(v7.getValue()) println(v8.getValue()) }
欢迎讨论,相互学习。
cdtxw@foxmail.com
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
2023-08-04 AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.3.0\cores\esp8266/../../bootloaders/eboot/flash.h:16:32: fatal error: spi_flash_geometry.h:
2021-08-04 OpenOCD-HI3861-RISCV使用方法 (JTAG/DTM+SWD/CoreSight)调试器仿真器
2021-08-04 c#字符串序列化-字符串转对象转字符串