将JSON字符串序列化为动态对象

好的,如果我的术语有误,请原谅我。 我试图做以下事情。

  1. 从URL获取JSON字符串
  2. 将所述字符串解析为一个对象。

通常对我来说这很容易。 通常,JSON对象是静态名称。

出现问题的地方是子json对象因人而异。 如果您更改库存,它们也会发生变化。

现在,我需要能够将它放入一个对象中,然后查询它(不一定是linq,而是随意拉取数据)。 有没有人有任何信息? 我试图创建一个动态对象(如此处所示将JSON反序列化为C#动态对象? )但它对我不起作用。

该链接是否真的符合我的目的,我是否只是错误地实现了它?

以下是JSON的转储: http : //chopapp.com/#ro46jfay

谢谢你的帮助。

Newtonsoft Json.net支持从json创建动态对象。

var obj = JsonConvert.DeserializeObject(json); 

实际上,您的数据并不像您想象的那样动态。 所有这些用作属性名称的ID都可以反序列化为Dictionary

虽然你的json比这个问题中的json更复杂,但同样的想法可以很容易地使用。

所以你的模型可以如下:

 public class RGInventory { public string id { get; set; } public string classid { get; set; } public string instanceid { get; set; } public string amount { get; set; } public int pos { get; set; } } public class AppData { public string def_index { get; set; } public int is_itemset_name { get; set; } } public class Description { public string type { get; set; } public string value { get; set; } public string color { get; set; } public AppData app_data { get; set; } } public class Action { public string name { get; set; } public string link { get; set; } } public class MarketAction { public string name { get; set; } public string link { get; set; } } public class Tag { public string internal_name { get; set; } public string name { get; set; } public string category { get; set; } public string category_name { get; set; } public string color { get; set; } } public class RGDescription { public string appid { get; set; } public string classid { get; set; } public string instanceid { get; set; } public string icon_url { get; set; } public string icon_url_large { get; set; } public string icon_drag_url { get; set; } public string name { get; set; } public string market_hash_name { get; set; } public string market_name { get; set; } public string name_color { get; set; } public string background_color { get; set; } public string type { get; set; } public int tradable { get; set; } public int marketable { get; set; } public int commodity { get; set; } public string market_tradable_restriction { get; set; } public List descriptions { get; set; } public List actions { get; set; } public List market_actions { get; set; } public List tags { get; set; } } public class RootObject { public bool success { get; set; } public bool more { get; set; } public bool more_start { get; set; } public Dictionary rgInventory { get; set; } public Dictionary rgDescriptions { get; set; } } 

现在你可以反序列化(使用Json.Net )

 var obj = JsonConvert.DeserializeObject(json); 

层次结构如下:ROOT – > rgDescriptios – > RandomName如何访问所有随机名称及其子项?

样本linq可以写成

 var appids = obj.rgDescriptions.Select(x => x.Value.appid).ToList(); 

以类型安全的方式。