读取DataTable时出现意外的JSON令牌.预期的StartArray,获得了StartObject [英] Unexpected JSON token when reading DataTable. Expected StartArray, got StartObject

查看:423
本文介绍了读取DataTable时出现意外的JSON令牌.预期的StartArray,获得了StartObject的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个有效的json(任何json字符串)字符串,并试图将其转换为Dataset,但Newtonsoft.Json失败了.

I have a valid json (any json string) string and trying to convert it to Dataset but Newtonsoft.Json failed to do so.

Json文字:

  {"root": {
  "Item": [
    {
      "Name": "Super Mario Bros",
      "Count": "14",
      "Price": "29,99",
      "Comment": "-No Comment-",
      "Artist": "N/A",
      "Publisher": "Nintendo",
      "Genre": "Video Games",
      "Year": "1985",
      "ProductID": "001"
    },
    {
      "Name": "The Legend of Zelda",
      "Count": "12",
      "Price": "34,99",
      "Comment": "-No Comment-",
      "Artist": "N/A",
      "Publisher": "Nintendo",
      "Genre": "Video Games",
      "Year": "1986",
      "ProductID": "002"
    }
  ]
}
}

代码:

var table = JsonConvert.DeserializeObject<DataSet>(jsonText);

错误:

读取DataTable时出现意外的JSON令牌.应该是StartArray,得到了StartObject.路径"root",第1行,位置9.

Unexpected JSON token when reading DataTable. Expected StartArray, got StartObject. Path 'root', line 1, position 9.

用户可以传递任何类型的json,我需要将其转换为DataSet 对于上面的示例,"root"元素可以包含任何其他属性 例如"child1":"val1","child2":"val2",依此类推.所以,输出 数据集将包含2个表namse root(应该有1行 属性1和2)和项(应该具有名称,计数,价格类型的2行) 等).

user can pass any type of json and i need to convert it to DataSet for the above example "root" element can contain any other property like "child1":"val1", "child2":"val2" and so forth. so, the output dataset will contain 2 tables namse root(should have one rows of properties 1 and 2) and item(should have 2 rows of type name,count,price etc).

推荐答案

您显示的Json无效.

The Json you showed is invalid.

应该看起来像这样,才能加载到DataSet:

It should look like this, to be load to the DataSet:

{
  "Item": [
    {
      "Name": "Super Mario Bros",
      "Count": "14",
      "Price": "29,99",
      "Comment": "-No Comment-",
      "Artist": "N/A",
      "Publisher": "Nintendo",
      "Genre": "Video Games",
      "Year": "1985",
      "ProductID": "001"
    },
    {
      "Name": "The Legend of Zelda",
      "Count": "12",
      "Price": "34,99",
      "Comment": "-No Comment-",
      "Artist": "N/A",
      "Publisher": "Nintendo",
      "Genre": "Video Games",
      "Year": "1986",
      "ProductID": "002"
    }
  ]
}

代码:

var dataSet = JsonConvert.DeserializeObject<DataSet>(jsonText);
var table = dataSet.Tables[0];

这篇关于读取DataTable时出现意外的JSON令牌.预期的StartArray,获得了StartObject的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆