使用Json.NET转换器,反序列化的属性转换器、属性、序列化、Json

2023-09-02 10:18:00 作者:狼狈

我有一个包含返回的接口属性一类的定义。

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属性或转换器,将让我指定一​​个具体的的东西类反序列化过程中使用?

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,这使得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特异性。该 $类型将是一个完全合格的类型,所以如果你它序列化与类型信息,,解串器需要能够理解它。

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.

文件:Serialization与Json.NET设置