c# - 如何使用 Newtonsoft Json.Net 反序列化接口(interface)

标签 c# .net json serialization 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; }
}

以及它们对应的接口(interface)
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 无法转换接口(interface)。

我发现了这篇很有前途的文章:

https://www.c-sharpcorner.com/UploadFile/20c06b/deserializing-interface-properties-with-json-net/



但我不确定如何使用该属性,因为在我的情况下,该属性是一个接口(interface)列表。

最佳答案

知道了!

文章中提供的转换器工作得非常好,我只是缺少在集合属性上使用它的语法。这是带有转换器和工作属性的代码:

// 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; }
}

关于c# - 如何使用 Newtonsoft Json.Net 反序列化接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50613560/

相关文章:

php - 想在php中发送和接收json数据

javascript - 将 JS 对象字符串化为 JSON(将函数字符串化为属性)

javascript - 将数组转换为 JSON 数组

c# - 如何删除 Azure 服务总线主题上的死信消息

c# - 从 C# .NET 流式传输时从 HTML5 视频获取导航功能

.net - PowerShell:创建自定义异常

c# - 升级应用程序时安装到同一路径

c# - 在 .NET 中更改 DateTimePicker 的背景颜色

c# - 使用 LINQ "everywhere"时的性能问题?

c# - SendKeys Ctrl-A 不工作