gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 01:32:13 26 4
gpt4 key购买 nike

我有一些对象:

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com