c# - 如何使用 Newtonsoft Json.Net 反序列化接口
问题描述
我有这个类层次结构:
public class ProxyBotsSnapshotLogEntryDetails : IBotsSnapshotLogEntryDetails
{
public ICollection<IBotSnapshot> Snapshots { get; set; }
}
public class ProxyBotSnapshot : IBotSnapshot
{
public string Name { get; set; }
public ICollection<IBotSnapshotItem> States { get; set; }
}
public class ProxyBotSnapshotItem : IBotSnapshotItem
{
public int Count { get; set; }
public IrcBotChannelStateEnum State { get; set; }
}
及其对应的接口
public interface IBotsSnapshotLogEntryDetails
{
ICollection<IBotSnapshot> Snapshots { get; set; }
}
public interface IBotSnapshot
{
string Name { get; set; }
ICollection<IBotSnapshotItem> States { get; set; }
}
public interface IBotSnapshotItem
{
int Count { get; set; }
IrcBotChannelStateEnum State { get; set; }
}
我想从 JSON 反序列化:
var test = JsonConvert.DeserializeObject<ProxyBotsSnapshotLogEntryDetails>(entry.DetailsSerialized);
但我收到一条错误消息,说 Newtonsoft 无法转换接口。
我发现了这篇很有前途的文章:
https://www.c-sharpcorner.com/UploadFile/20c06b/deserializing-interface-properties-with-json-net/
但我不确定如何使用该属性,因为在我的情况下,该属性是一个接口列表。
解决方案
知道了!
文章中提供的转换器工作得非常好,我只是错过了在集合属性上使用它的语法。这是带有转换器和工作属性的代码:
// From the article
public class ConcreteConverter<T> : JsonConverter
{
public override bool CanConvert(Type objectType) => true;
public override object ReadJson(JsonReader reader,
Type objectType, object existingValue, JsonSerializer serializer)
{
return serializer.Deserialize<T>(reader);
}
public override void WriteJson(JsonWriter writer,
object value, JsonSerializer serializer)
{
serializer.Serialize(writer, value);
}
}
public class ProxyBotsSnapshotLogEntryDetails : IBotsSnapshotLogEntryDetails
{
[JsonProperty(ItemConverterType = typeof(ConcreteConverter<ProxyBotSnapshot>))]
public ICollection<IBotSnapshot> Snapshots { get; set; }
}
public class ProxyBotSnapshot : IBotSnapshot
{
public string Name { get; set; }
[JsonProperty(ItemConverterType = typeof(ConcreteConverter<ProxyBotSnapshotItem>))]
public ICollection<IBotSnapshotItem> States { get; set; }
}
public class ProxyBotSnapshotItem : IBotSnapshotItem
{
public int Count { get; set; }
public IrcBotChannelStateEnum State { get; set; }
}
推荐阅读
- blazor - 如何在 Blazor 服务器端应用程序中处理异步取消
- python - 我必须复制和粘贴一个包吗?
- firebase - 如何使用 Firebase 在 Flutter 中登录用户的电子邮件
- google-cloud-platform - 使用 Terraform 和 Google Cloud Platform 在云中创建端点
- macos - SwiftUI NSVisualEffectView 看起来不透明?
- java - 如果函数参数的类型相同,为什么在 Java 中强制转换函数调用的两个参数是多余的?
- google-chrome-extension - 使用 chrome 扩展在 mail.google.com 上注入脚本
- visual-studio - Visual Studio Installer 项目始终安装 .NET Framework 4.8 必备组件,即使已安装
- javascript - 循环遍历数组(`Object.keys(obj)`)以查找值
- flutter - 如何在appBar中为flutter中的gridview列表实现搜索栏