Json.net序列化/反序列化派生类型?

时间:2021-07-30 17:02:47

json.net (newtonsoft)
I am looking through the documentation but I can't find anything on this or the best way to do it.

json.net (newtonsoft)我正在查阅文档,但是我找不到任何相关的东西,也找不到最好的方法。

public class Base
{
    public string Name;
}
public class Derived : Base
{
    public string Something;
}

JsonConvert.Deserialize<List<Base>>(text);

Now I have Derived objects in the serialized list. How do I deserialize the list and get back derived types?

现在我已经在序列化列表中派生了对象。如何反序列化列表并返回派生类型?

2 个解决方案

#1


26  

If you are storing the type in your text (as you should be in this scenario), you can use the JsonSerializerSettings.

如果您正在文本中存储类型(正如您在本场景中应该做的那样),您可以使用JsonSerializerSettings。

See: how to deserialize JSON into IEnumerable<BaseType> with Newtonsoft JSON.NET

参见:如何使用Newtonsoft JSON.NET将JSON反序列化为IEnumerable

#2


70  

You have to enable Type Name Handling and pass that to the (de)serializer as a settings parameter.

您必须启用类型名称处理,并将其作为设置参数传递给(反)序列化器。

Base object1 = new Base() { name = "Object1" };
Derived object2 = new Derived() { something = "Some other thing" };
List<Base> inheritanceList = new List<Base>() { object1, object2 };

JsonSerializerSettings settings = new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.All };
string Serialized = JsonConvert.SerializeObject(inheritanceList, settings);
List<Base> deserializedList = JsonConvert.DeserializeObject<List<Base>>(Serialized, settings);

This will result in correct desirialization of derived classes. A drawback to it is that it will name all the objects you are using, as such it will name the list you are putting the objects in.

这将导致派生类的正确设计。它的一个缺点是它将命名所有你正在使用的对象,因为这样它会列出你要放入对象的列表。

#1


26  

If you are storing the type in your text (as you should be in this scenario), you can use the JsonSerializerSettings.

如果您正在文本中存储类型(正如您在本场景中应该做的那样),您可以使用JsonSerializerSettings。

See: how to deserialize JSON into IEnumerable<BaseType> with Newtonsoft JSON.NET

参见:如何使用Newtonsoft JSON.NET将JSON反序列化为IEnumerable

#2


70  

You have to enable Type Name Handling and pass that to the (de)serializer as a settings parameter.

您必须启用类型名称处理,并将其作为设置参数传递给(反)序列化器。

Base object1 = new Base() { name = "Object1" };
Derived object2 = new Derived() { something = "Some other thing" };
List<Base> inheritanceList = new List<Base>() { object1, object2 };

JsonSerializerSettings settings = new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.All };
string Serialized = JsonConvert.SerializeObject(inheritanceList, settings);
List<Base> deserializedList = JsonConvert.DeserializeObject<List<Base>>(Serialized, settings);

This will result in correct desirialization of derived classes. A drawback to it is that it will name all the objects you are using, as such it will name the list you are putting the objects in.

这将导致派生类的正确设计。它的一个缺点是它将命名所有你正在使用的对象,因为这样它会列出你要放入对象的列表。