简体   繁体   English

JSON字符串到对象数组C#

[英]Json string to object array c#

My test json is as below.. 我的测试json如下。

 string json = "[{Name:'John Simith',Age:35},{Name:'Pablo Perez',Age:34}]"; 

The json could have any key values and so I do not have a class to deserialize it with.. I can deserialize it as IEnumerable as below json可以具有任何键值,因此我没有一个类可以反序列化。.我可以将其反序列化为IEnumerable,如下所示

IEnumerable<dynamic> data = JsonConvert.DeserializeObject<IEnumerable<dynamic>>(json);

I need to convert it to 2D object arrays : object[,] as below.. 我需要将其转换为2D对象数组:object [,]如下。

[
['John Simith',35],['Pablo Perez',34]
]

Any help is sincerely appreciated. 真诚的感谢您的帮助。 Thanks 谢谢

If you don't have a C# class to deserialize it to, the best thing to do is to use the dynamic LINQ objects that JSON.NET provides, meaning JObject , JArray and so on. 如果没有将其反序列化的C#类,则最好的办法是使用JSON.NET提供的动态LINQ对象,即JObjectJArray等。 This lets you query the structure dynamically, read types values and so on, without having to fight with C#'s type system: 这使您可以动态查询结构,读取类型值等,而不必与C#的类型系统抗争:

http://www.newtonsoft.com/json/help/html/ParsingLINQtoJSON.htm http://www.newtonsoft.com/json/help/html/ParsingLINQtoJSON.htm

It would be much easier to traverse the JSON tree and convert to object[,] from those objects. 遍历JSON树并从那些对象转换为object[,]会容易得多。

You can change from dynamic to IDictionary<string, object> in order to be able to enumerate unknown keys. 您可以从dynamic更改为IDictionary<string, object> ,以便能够枚举未知键。 Then a LINQ expression can convert it to an array, like this: 然后,LINQ表达式可以将其转换为数组,如下所示:

var json = "[{Name:'John Simith',Age:35},{Name:'Pablo Perez',Age:34}]";
var data = JsonConvert.DeserializeObject<IEnumerable<IDictionary<string, object>>>(json);

var array = data.Select(d => d.Values.ToArray()).ToArray();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM