C#json DeserializeObject继承

时间:2013-08-21 13:07:00

标签: c# json

我有一个Parent类和一个Child类,json字符串包含Child类的属性,但是当我执行DeserializeObject时,我无法获取这些属性,因为Child成为了Parent。

例如:

class Data {
    public List<Parent> Parents;
}

class Parent {
    public string Foo;
}

class Child : Parent {
    public string Bar;
}

var data = new Data { Parents = new List<Parent> { new Child{Bar = "a"} } };
Console.WriteLine(data.Parents.Count); // <= it prints 1
Console.WriteLine(data.Parents.OfType<Child>().Count()); // <= it prints 1

var dataJson = JsonConvert.SerializeObject(data);
data = JsonConvert.DeserializeObject<Data>(dataJson);

Console.WriteLine(data.Parents.Count); // <= it prints 1
Console.WriteLine(data.Parents.OfType<Child>().Count()); // <= it prints 0 instead of 1

我该怎么办? Newtonsoft.Json可以设法做我想做的事情吗?

1 个答案:

答案 0 :(得分:4)

使用JsonSerializerSettings' TypeNameHandling

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

var dataJson = JsonConvert.SerializeObject(data, settings);
data = JsonConvert.DeserializeObject<Data>(dataJson, settings);