C# 如何使用Json.NET重建我的类层次结构?

C# 如何使用Json.NET重建我的类层次结构?,c#,json,serialization,C#,Json,Serialization,我有一个简单的类层次结构。Foo是基类。Bar和Baz是从Foo继承的。这些类的实例存储在列表中。我必须将列表序列化为JSON。它工作得很好。但问题是将其反序列化回列表中 我把Foos、bar和baz放在列表中,序列化它,当我反序列化它时,我只得到Foos:)不过我想要我的bar和baz。这在Json.NET中是可能的吗 using System; using System.Collections.Generic; using Newtonsoft.Json; namespace JsonT

我有一个简单的类层次结构。Foo是基类。Bar和Baz是从Foo继承的。这些类的实例存储在列表中。我必须将列表序列化为JSON。它工作得很好。但问题是将其反序列化回列表中

我把Foos、bar和baz放在列表中,序列化它,当我反序列化它时,我只得到Foos:)不过我想要我的bar和baz。这在Json.NET中是可能的吗

using System;
using System.Collections.Generic;

using Newtonsoft.Json;

namespace JsonTest
{
  class Foo
  {
    int number;

    public Foo(int number)
    {
      this.number = number;
    }

    public int Number
    {
      get { return number; }
      set { number = value; }
    }
  }

  class Bar : Foo
  {
    string name;

    public Bar(int number, string name)
      : base(number)
    {
      this.name = name;
    }

    public string Name
    {
      get { return name; }
      set { name = value; }
    }
  }

  class Baz : Foo
  {
    float time;

    public Baz(int number, float time)
      : base(number)
    {
      this.time = time;
    }

    public float Time
    {
      get { return time; }
      set { time = value; }
    }
  }

  class Program
  {
    static void Main(string[] args)
    {
      List<Foo> fooList = new List<Foo>();
      fooList.Add(new Foo(123));
      fooList.Add(new Bar(123, "Hello, world"));
      fooList.Add(new Baz(123, 0.123f));

      string json = JsonConvert.SerializeObject(fooList, Formatting.Indented);
      List<Foo> fooList2 = JsonConvert.DeserializeObject<List<Foo>>(json);
      // Now I have only Foos in the List
    }
  }
}
使用系统;
使用System.Collections.Generic;
使用Newtonsoft.Json;
名称空间JsonTest
{
福班
{
整数;
公共食品(国际编号)
{
这个数字=数字;
}
公共整数
{
获取{返回编号;}
设置{number=value;}
}
}
酒吧类别:富
{
字符串名;
公共栏(整数、字符串名称)
:基数(数字)
{
this.name=名称;
}
公共字符串名
{
获取{返回名称;}
设置{name=value;}
}
}
类别Baz:Foo
{
浮动时间;
公共Baz(整数、浮动时间)
:基数(数字)
{
这个时间=时间;
}
公共浮动时间
{
获取{返回时间;}
设置{time=value;}
}
}
班级计划
{
静态void Main(字符串[]参数)
{
列表傻瓜=新列表();
添加(新富(123));
添加(新的酒吧(123,“你好,世界”);
添加(新Baz(123,0.123f));
字符串json=JsonConvert.SerializeObject(傻瓜,格式化,缩进);
List WOULIST2=JsonConvert.DeserializeObject(json);
//现在我的名单上只有食物
}
}
}

您正在序列化的是食物列表,而不是Baz和Bar列表。
我认为保持逻辑的最简单解决方案是序列化Baz和Bars的列表,并在列表中添加concat(只有当您可以使用不同的顺序时,这才有效)。

一般来说,使用这种设计看起来并不自然。最好让一个类具有不同的构造函数,并在字段不适用时使用null。

Hm。。。但是,Bar和Baz的所有字段都序列化为JSON。调用JsonConvert.SerializeObject后,JSON中有Bar的name字段和Baz的time字段。只有另一种方法是行不通的。反序列化JSON给了我三个foo。它只是忽略特定于Bar和Baz的字段。我认为Json.NET可能有一个聪明的技巧(比如属性)来保持我的类层次结构。