在JSON.NET中反序列化具有不同名称的对象列表

我从一个网站上获取我的数据,该网站返回一个我不太熟悉的.json格式。 我一直在寻找解决方案几个小时,我必须使用术语。

json的格式如下:

[ { "Foo": { "name": "Foo", "size": { "human": "832.73kB", "bytes": 852718 }, "date": { "human": "September 18, 2017", "epoch": 1505776741 }, } }, { "bar": { "name": "bar", "size": { "human": "4.02MB", "bytes": 4212456 }, "date": { "human": "September 18, 2017", "epoch": 1505776741 } } }] 

我正在使用Newtonsoft的JSON.NET,我似乎无法创建一个允许我反序列化它的数据结构,因为它是具有不同名称的类数组。 具体而言,属性名称"Foo""bar"在运行时可能不同。 JSON层次结构中其他位置的属性名称是已知的。

假设在编译时只有名称"Foo""Bar"是未知的,您可以将该JSON反序列化为List> ,其中RootObject是ac#model我使用http:// json2csharp自动生成.com /来自JSON的"Foo"值。

楷模:

 public class Size { public string human { get; set; } public int bytes { get; set; } } public class Date { public string human { get; set; } public int epoch { get; set; } } public class RootObject { public string name { get; set; } public Size size { get; set; } public Date date { get; set; } } 

反序列化代码:

 var list = JsonConvert.DeserializeObject>>(jsonString); 

笔记:

  • 最外面的类型必须是可枚举的List因为最外面的JSON容器是一个数组 – 由[]包围的逗号分隔的值序列。 请参见序列化指南:IEnumerable,Lists和Arrays 。

  • 当JSON对象可以具有任意属性名称但具有固定的属性值模式时,可以将其反序列化为Dictionary以获取适当的T 请参阅反序列化字典 。

  • 可能bytesepoch应该是long类型。

工作.Net小提琴 。