使用Json.NET转换器,反序列化的属性 [英] Using Json.NET converters to deserialize properties

查看:180
本文介绍了使用Json.NET转换器,反序列化的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

文件:<一href="http://james.newtonking.com/projects/json/help/index.html?topic=html/SerializationSettings.htm">Serialization与Json.NET设置

这篇关于使用Json.NET转换器,反序列化的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆