且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用Json.Net问题解析JSON到DataSet

更新时间:2023-01-17 19:41:46

它不工作的原因是因为你的JSON数据不符合结构就需要以反序列化到数据集。如果你看看在例如从文档,数据需要像这样的结构:

The reason it doesn't work is because your JSON data doesn't conform to the structure it would need to in order to deserialize into a DataSet. If you take a look at the example from the documentation, the data needs to be structured like this:

{
    "table1" : 
    [
        {
            "column1" : "value1",
            "column2" : "value2"
        },
        {
            "column1" : "value3",
            "column2" : "value4"
        }            
    ],
    "table2" : 
    [
        {
            "column1" : "value1",
            "column2" : "value2"
        },
        {
            "column1" : "value3",
            "column2" : "value4"
        }            
    ]
}

在换句话说,外对象包含代表表格属性。属性名对应表的名称,和值,其中每个对象代表表中的一行对象的所有阵列。该对象的属性对应的列名,其值是该行的数据。行的数据值必须是简单的类型,如字符串,整数,布尔等(简单类型和嵌套的数据表数组,如果你正在使用Json.Net 6.0或更高版本也支持。)

In other words, the outer object contains properties which represent tables. The property names correspond to the names of the tables, and the values are all arrays of objects where each object represents one row in the table. The objects' properties correspond to the column names, and their values are the row data. The row data values must be simple types such as string, int, bool, etc. (Arrays of simple types and nested data tables are also supported if you're using Json.Net 6.0 or later.)

您的JSON数据比这要复杂得多,而且是深度嵌套。你将无法得到Json.Net将其反序列化到DataSet,除非你编写自己的定制JsonConverter做到这一点。 。我不认为这是值得的,这样做

Your JSON data is MUCH more complex than this, and is deeply nested. You will not be able to get Json.Net to deserialize it into a DataSet unless you write your own custom JsonConverter to do it. And I don't think it would be worth the effort to do so.

相反,我会考虑这些其他的替代品之一:

Instead, I would consider one of these other alternatives:


  1. 创建一个强类型的类层次结构和反序列化到该。您可以使用 json2csharp.com 以帮助生成你的类。 (请注意,但是,json2csharp并非万无一失 - 有时你需要编辑它生成得到的东西正常工作类)

  2. 反序列化到一个 JObject 和使用Json.Net的 LINQ到-JSON API 浏览和提取所需的数据。这里是 ,一个例子可能与帮助。有文档中许多其他的例子还有这里的计算器。

  3. 反序列化到一个动态。这种方法使得它很容易让你的数据,假设你知道它的结构很好,但你失去了智能感知和编译时检查。

  1. Create a strongly-typed class hierarchy and deserialize into that. You can use json2csharp.com to help generate your classes. (Note, however, that json2csharp is not foolproof--sometimes you will need to edit the classes it generates to get things to work properly.)
  2. Deserialize into a JObject and use Json.Net's LINQ-to-JSON API to navigate and extract the data you need. Here is an example that might help with that. There are many other examples in the documentation as well as here on ***.
  3. Deserialize into a dynamic. This approach makes it pretty easy to get at your data, assuming you know its structure well, but you lose intellisense and compile-time checking.