first version
This commit is contained in:
@@ -0,0 +1,88 @@
|
||||
/*
|
||||
* Copyright (c) 2025 SimcuTeam. All rights reserved.
|
||||
* 移植自 C# 项目 SimApi(E:\simcu\simapi-net),遵循 MIT 许可证。
|
||||
*/
|
||||
|
||||
package simapi.communications
|
||||
|
||||
import std.collection.*
|
||||
import stdx.encoding.json.*
|
||||
import soulsoft_serialization.*
|
||||
|
||||
/**
|
||||
* 带任意对象数据的响应(非泛型版,供响应自动封装使用)。
|
||||
*
|
||||
* 与 SimApiResponse<T> 的区别:data 为 Any(运行时类型不定),用于
|
||||
* SimApiRequestDelegateFactory 派发结果时统一包装 DTO/数组/动态结构。
|
||||
*
|
||||
* 序列化规则(对齐 SimApiResponse<T>):
|
||||
* - data 实现了 ISerializable(@Serialization DTO、Array<T> 等)→ data 内嵌为对象
|
||||
* - data 为动态结构(如 HashMap<String, Any>,不满足泛型 ISerialization 约束)
|
||||
* → 经 SimApiJson 序列化后解析内嵌为对象(而非字符串)
|
||||
* 因此 data 在 JSON 中始终是对象/数组/标量,不会是"JSON 字符串"。
|
||||
*/
|
||||
public class SimApiDataResponse <: SimApiBaseResponse & ISerialization<SimApiDataResponse> {
|
||||
public var _data: ?Any = None
|
||||
|
||||
public init() {
|
||||
super()
|
||||
}
|
||||
|
||||
public init(data: Any) {
|
||||
super()
|
||||
this._data = Some(data)
|
||||
}
|
||||
|
||||
public init(code: Int64, message: String) {
|
||||
super(code, message)
|
||||
}
|
||||
|
||||
public init(code: Int64, message: String, data: Any) {
|
||||
super(code, message)
|
||||
this._data = Some(data)
|
||||
}
|
||||
|
||||
/**
|
||||
* 序列化为 DataModel:code + message + data(data 为对象)。
|
||||
*/
|
||||
public override func serializeObject(options: JsonSerializerOptions): DataModel {
|
||||
let dms = DataModelStruct()
|
||||
dms.add(Field("code", DataModelInt(_code)))
|
||||
dms.add(Field("message", DataModelString(_message)))
|
||||
if (let Some(data) <- _data) {
|
||||
if (let ser: ISerializable <- data) {
|
||||
dms.add(Field("data", ser.serializeObject(options)))
|
||||
} else {
|
||||
// 动态结构(HashMap<String, Any> 等):经 SimApiJson 序列化后解析内嵌为对象
|
||||
let json = SimApiJson.json(Some(data))
|
||||
dms.add(Field("data", DataModel.fromJson(JsonValue.fromStr(json))))
|
||||
}
|
||||
}
|
||||
dms
|
||||
}
|
||||
|
||||
/**
|
||||
* 从 DataModel 反序列化:code + message + data(data 保留原始 DataModel)。
|
||||
*/
|
||||
public static func deserializeObject(dm: DataModel, options: JsonSerializerOptions): SimApiDataResponse {
|
||||
let resp = SimApiDataResponse()
|
||||
if (let dms: DataModelStruct <- dm) {
|
||||
for (field in dms.getFields()) {
|
||||
match (field.getName()) {
|
||||
case "code" =>
|
||||
if (let v: DataModelInt <- field.getData()) {
|
||||
resp._code = v.getValue()
|
||||
}
|
||||
case "message" =>
|
||||
if (let v: DataModelString <- field.getData()) {
|
||||
resp._message = v.getValue()
|
||||
}
|
||||
case "data" =>
|
||||
resp._data = Some(field.getData())
|
||||
case _ => ()
|
||||
}
|
||||
}
|
||||
}
|
||||
resp
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user