使用 Json.NET 转换器反序列化属性 [英] Using Json.NET converters to deserialize properties
问题描述
我有一个类定义,其中包含一个返回接口的属性.
I have a class definition that contains a property that returns an interface.
public class Foo
{
public int Number { get; set; }
public ISomething Thing { get; set; }
}
尝试使用 Json.NET 序列化 Foo 类会给我一条错误消息,例如无法创建类型为 'ISomething' 的实例.ISomething 可能是一个接口或抽象类."
Attempting to serialize the Foo class using Json.NET gives me an error message like, "Could not create an instance of type 'ISomething'. ISomething may be an interface or abstract class."
是否有 Json.NET 属性或转换器可以让我指定一个具体的 Something
类在反序列化期间使用?
Is there a Json.NET attribute or converter that would let me specify a concrete Something
class to use during deserialization?
推荐答案
您可以使用 Json.NET 是:
var settings = new JsonSerializerSettings();
settings.TypeNameHandling = TypeNameHandling.Objects;
JsonConvert.SerializeObject(entity, Formatting.Indented, settings);
TypeNameHandling
标志将向 JSON 添加一个 $type
属性,这允许 Json.NET 知道它需要将对象反序列化为哪种具体类型.这允许您在实现接口或抽象基类的同时反序列化对象.
The TypeNameHandling
flag will add a $type
property to the JSON, which allows Json.NET to know which concrete type it needs to deserialize the object into. This allows you to deserialize an object while still fulfilling an interface or abstract base class.
然而,缺点是这是非常特定于 Json.NET 的.$type
将是完全限定的类型,因此如果您使用类型信息对其进行序列化,则反序列化器也需要能够理解它.
The downside, however, is that this is very Json.NET-specific. The $type
will be a fully-qualified type, so if you're serializing it with type info,, the deserializer needs to be able to understand it as well.
这篇关于使用 Json.NET 转换器反序列化属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!