2

我有一个 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 可以做我想做的事吗?

4

1 回答 1

5

利用JsonSerializerSettings' TypeNameHandling

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

var dataJson = JsonConvert.SerializeObject(data, settings);
data = JsonConvert.DeserializeObject<Data>(dataJson, settings);
于 2013-08-21T13:20:56.770 回答