简体   繁体   English

如何将 JSON object 反序列化为使用派生类的 C# ZA2F2ED4F8EBC2CBB4C21A29DC40AB6?

[英]How do I deserialise a JSON object to a C# class that uses derived classes?

I have the following classes which I am serialising and deserialising to and from JSON using Json.NET :我有以下类,我使用Json.NET对 JSON 进行序列化和反序列化:

public class Message
{
  public Guid MessageId { get; set; }
  public List<Task> Tasks { get; set; }
}

public class Task
{
  public int TaskId { get; set; }
}

public SomeTask : Task
{
  public string SomeTaskThing { get; set; }
  public List<string> Operations { get; set; }
}

public OtherTask : Task
{
  public int OtherTaskThing { get; set; }
  public List<int> MoreOtherTaskThings { get; set; }
}

A Message basically consists of a list of SomeTask and OtherTask Task s which I pass across the wire to a message processor that also knows about these classes. Message基本上由SomeTaskOtherTask Task的列表组成,我将它们通过线路传递到也知道这些类的消息处理器。

When I serialise a Message I do the following:当我序列化Message时,我会执行以下操作:

string json = JsonConvert.SerializeObject(
        message, 
        Formatting.Indented, 
        new JsonSerializerSettings
          {
            TypeNameHandling = TypeNameHandling.Objects
          });

My derived classes are serialised as I would expect along with $type names embedded in the JSON.我的派生类与嵌入在 JSON 中的$type名称一起被序列化。

However when I deserialise the JSON string back to a Message object the deserialiser doesn't rehydrate my derived class objects.但是,当我将 JSON 字符串反序列化回Message object 时,反序列化器不会再水化我派生的 class 对象。 I just get a list of the base class Task .我只是得到一个基本 class Task的列表。

I thought $type added to the JSON string by using TypeNameHandling = TypeNameHandling.Objects might have provided a hint to the deserialiser about which classes to instantiate, but I was wrong.我认为$type通过使用TypeNameHandling = TypeNameHandling.Objects添加到 JSON 字符串中可能已经向反序列化器提供了关于要实例化哪些类的提示,但我错了。

What do I need to do to deserialise objects who's base class is Task and rehydrate the derived classes into the List<Task> ?我需要做什么来反序列化以 class 为基础的对象,并将派生类重新水合到List<Task> Task

I'm limited to .NET Framework 3.5 for this project.对于这个项目,我仅限于 .NET Framework 3.5。

Make sure you are using the same JsonSerializerSettings to deserialize as well.确保您也使用相同的JsonSerializerSettings进行反序列化。 It doesn't have to be the same instance but it must have TypeNameHandling = TypeNameHandling.Objects set in order to work on deserialization.它不必是同一个实例,但必须设置TypeNameHandling = TypeNameHandling.Objects才能进行反序列化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM