c# - 使用 Json.net 反序列化混合类型列表

标签 c# serialization json.net

我正在使用 Json.Net 并尝试序列化和反序列化包含多种类型对象的列表。我正在努力寻找一种方法来结束一个包含我的派生类型对象的列表,相反,我最终得到一个基本类型列表。

我的代码示例非常清楚发生了什么:

public class Vehicle{
    public int wheels = 4;
}
public class Truck : Vehicle {
    public int airhorns = 1;
}

static void Main (string[] args) {

    List<Vehicle> vehicles = new List<Vehicle> ();
    vehicles.Add (new Vehicle ());
    vehicles.Add (new Truck ());
    foreach (Vehicle v in vehicles) {
        Console.WriteLine ("Before deserializing, we have a: " + v.GetType ());
    }

    string s = JsonConvert.SerializeObject (vehicles);
    List<Vehicle> deserialized = JsonConvert.DeserializeObject<List<Vehicle>> (s);
    foreach (Vehicle v in deserialized) {
        Console.WriteLine ("After deserializing, we have a: " + v.GetType ());
    }
}

运行结果为:

Before deserializing, we have a: Vehicle
Before deserializing, we have a: Truck
After deserializing, we have a: Vehicle
After deserializing, we have a: Vehicle

我想在我的反序列化列表中添加一辆卡车。需要注意的一件事是字符串“s”中的 json 确实包含 airhorns 变量。这样数据就存在了。

我浏览了 JSON 文档,但没有找到任何能完全满足我的要求的内容。我研究了黑客 CustomCreationConverters ( http://james.newtonking.com/json/help/index.html?topic=html/CustomCreationConverter.htm ),看起来它们可能被用来实例化正确的派生类,但该方法不提供任何 json 数据,所以我无法确定类型。

我愿意添加另一个可能明确定义“Class:Vehicle”或“Class:Truck”的字段,但我还不确定如何使用它。也许在创建正确的类之后,我可以在新对象上使用 JsonConvert.PopulateObject...但是我需要处理 json 片段。

有什么想法吗?谢谢!

最佳答案

只需设置 TypeNameHandling 并在序列化和反序列化中使用此设置。

var settings = new JsonSerializerSettings() { 
                  TypeNameHandling = Newtonsoft.Json.TypeNameHandling.All
               };

string s = JsonConvert.SerializeObject(vehicles, settings);
List<Vehicle> deserialized = JsonConvert.DeserializeObject<List<Vehicle>>(s,settings);

foreach (Vehicle v in deserialized)
{
    Console.WriteLine("After deserializing, we have a: " + v.GetType());
}

输出:

Before deserializing, we have a: SO3.Form1+Vehicle
Before deserializing, we have a: SO3.Form1+Truck
After deserializing, we have a: SO3.Form1+Vehicle
After deserializing, we have a: SO3.Form1+Truck   

关于c# - 使用 Json.net 反序列化混合类型列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24686830/

相关文章:

c# - 我找不到 System.Windows.Media 命名空间

javascript - 如何从ajax调用MVC Controller 获取数据?

c# - 将 IP 异常(exception)添加到防火墙

.net - 在 .NET Web API 中设置 JSON 序列化的最大深度

c# - HttpClient GetStreamAsync 和 HTTP 状态代码?

c# - 根据系统时间自动更新自定义 DateTime 对象

serialization - 序列化 List<T> 子类失败

java - XStream-不包含某些值

serialization - 使用 NewtonSoft Json.Net 将简单字符串序列化为 BSON 时出错

c# - JSON 有效,但代码中的结果返回 null