如何反序列化JSON数据?

如何反序列化JSON数据?

问题描述:

我是使用JSON数据的新手.

I am new to working with JSON data.

我正在从Web服务读取数据.发送回的查询数据如下:

I am reading data from a web service. The query data sent back is the following:

[["B02001_001E","NAME","state"],
 ["4712651","Alabama","01"],
 ["691189","Alaska","02"],
 ["6246816","Arizona","04"],
 ["18511620","Florida","12"],
 ["9468815","Georgia","13"],
 ["1333591","Hawaii","15"],
 ["1526797","Idaho","16"],
 ["3762322","Puerto Rico","72"]]

是否有一种方法可以以这种方式反序列化此数据,而无需我先定义对象的样子就可以生成基础对象?在上面的示例中,对象是由第一行定义的:

Is there a way to Deserialize this data in such a way that the base object will be generated without me first defining what the object is like? In the above example the object is defined by the first row:

           ["B02001_001E","NAME","state"],

通常,Web服务将返回格式化为二维JSON数组的查询数据,其中第一行提供列名,随后的行提供数据值.

In general the web service will return the query data formatted as a two dimensional JSON array where the first row provides column names and subsequent rows provide data values.

您可以非常轻松地反序列化. C#中的数据结构只是List<string[]>,所以您可以这样做;

You can deserialize this really easily. The data's structure in C# is just List<string[]> so you could just do;

  List<string[]> data = JsonConvert.DeserializeObject<List<string[]>>(jsonString);

上面的代码假设您正在使用json.NET.

The above code is assuming you're using json.NET.

请注意,从技术上讲,json是字符串数组的数组.我更喜欢在自己的声明中使用List<string[]>,因为它更加直观.它不会对json.NET造成任何问题,如果您希望它是字符串数组的数组,那么您需要将类型更改为(我认为)string[][],但是有一些带有锯齿形和2D数组的有趣小陷阱在C#中我不太了解,所以我就不用在这里处理它了.

Note the json is technically an array of string arrays. I prefer to use List<string[]> for my own declaration because it's imo more intuitive. It won't cause any problems for json.NET, if you want it to be an array of string arrays then you need to change the type to (I think) string[][] but there are some funny little gotcha's with jagged and 2D arrays in C# that I don't really know about so I just don't bother dealing with it here.