C# Json.Deserialize with Object with Child class with interfaces

标签 c# json

我有一些对象:

public class MyObject
{
    public MyField Field { get; set; }
}

public class MyField
{
    [JsonProperty]
    public Entity MyEntity { get; set; }
    public IEntity IMyEntity { get; set; }
}

public interface IEntity
{
    string MyStr { get; }
}

public class Entity : IEntity
{
}

然后我尝试做类似的事情

JsonConvert.DeserializeObject<MyObject>(myObjStr); 

抛出类似的错误

Could not create an instance of type MyObject... Type is an interface or abstract class and cannot be instantiated. Path 'MyField.IMyEntity.MyInt'

我无法更改字段或实体,因为它在另一个组的代码库中。 MyObject 类在我的。有没有办法反序列化这个对象?我在这里尝试了一些使用 JsonSerializerSettings 的东西 JSON.NET - how to deserialize collection of interface-instances?但无济于事。

最佳答案

您可以创建自己的 JSON 转换器,它允许您指定类型映射:

public class JsonTypeMapper<TFromType, TToType> : JsonConverter
{
    public override bool CanConvert(Type objectType) => objectType == typeof(TFromType);

    public override object ReadJson(JsonReader reader,
     Type objectType, object existingValue, JsonSerializer serializer)
    {
        return serializer.Deserialize<TToType>(reader);
    }

    public override void WriteJson(JsonWriter writer,
        object value, JsonSerializer serializer)
    {
        serializer.Serialize(writer, value);
    }
}

然后你像这样反序列化:

JsonConvert.DeserializeObject<MyObject>(myObjStr, new JsonSerializerSettings
{
    Converters = new List<JsonConverter> { new JsonTypeMapper<IEntity, Entity>() }
                                                            //^^^^^^^, ^^^^^^
}); 

关于C# Json.Deserialize with Object with Child class with interfaces,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37871009/

相关文章:

C# 表达式转换为派生类型

c# - 使用 Parallel.For 创建列表列表 - 我做错了什么?

c# - 在 Windows Phone 8 中以非标准尺寸录制(或录制后转换)视频

javascript - 我如何在meteorjs中返回包含函数的对象?

python - 分组和缩进从 pandas 数据框创建的 json

c# - 定义精确大小的内存结构

c# - 属性函数的奇怪行为

c - 在 C 项目中包含 json-c

json - 如何将结构编码回字节缓冲区

ios - 在 UITableViewCell 上设置 JSON 值时出错