【发布时间】:2023-04-04 08:10:02
【问题描述】:
我正在使用无法更改的基于 JSON 的 API 进行通信。它总是返回一个 Response 对象,其中包含一个不同的 Result 对象。通常它看起来像这样:
{ "ver": "2.0", "result": { "code": 0 } }
对于某些命令,Result 对象是通过添加额外属性来“增长”的:
{ "ver": "2.0", "result": { "code": 0, "hostName": "sample", "hostPort": 5000 } }
我使用 Newtonsoft 属性来定义对象如下:
内部类 RpcResponse { [JsonProperty(PropertyName = "ver")] 公共字符串版本{获取;放; } [JsonProperty(PropertyName = "结果")] 公共 RpcResponseResult 结果 { 得到; 放; } 内部类 RpcResponseResult { [JsonProperty(PropertyName = "代码")] 公共 int 代码 { 获取;放; } } 内部类 RpcExtendedResponseResult: RpcResponseResult { [JsonProperty(PropertyName = "hostName")] 公共字符串主机名 { 获取;放; } [JsonProperty(PropertyName = "hostPort")] 公共 int 主机端口 { 获取;放; }但是当Response对象被反序列化时:
RpcResponse rspResponse = JsonConvert.DeserializeObject其 Result 属性始终显示为 RpcResponseResult 对象,即。 JsonConvert 不知道将其构造为 RpcExtendedResponseResult 对象。
属性或转换器有什么方法可以恢复正确的后代对象吗?我觉得我错过了一些明显的东西!
【问题讨论】:
-
你在寻找这样的东西吗stackoverflow.com/questions/3142495/…