c# - 读取 DataTable 时出现意外的 JSON 标记。预期的 StartArray,得到 StartObject

标签 c# json json.net

我有一个有效的 json(任何 json 字符串)字符串并尝试将其转换为数据集,但 Newtonsoft.Json 未能这样做。

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);

错误:

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



编辑1:

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).

最佳答案

它不起作用,因为代表 DataSet 的 JSON 对象不在 JSON 的根级别。在您的 JSON 中,它位于名为 root 的属性中。 ,它位于另一个包装器对象内。因此,您在反序列化时需要考虑该外部对象。您可以定义一个包装类并将其反序列化为:

public class Wrapper
{
    [JsonProperty("root")]
    public DataSet DataSet { get; set; }
}

然后:
DataSet ds = JsonConvert.DeserializeObject<Wrapper>(json).DataSet;

( Fiddle )

或者,如果你不想创建一个类,你可以反序列化为一个 JObject ,向下导航至 root属性,然后将其具体化为 DataSet从那里:
DataSet ds = JObject.Parse(json)["root"].ToObject<DataSet>();

( Fiddle )

关于c# - 读取 DataTable 时出现意外的 JSON 标记。预期的 StartArray,得到 StartObject,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48214807/

相关文章:

c# - ASPX 访问母版页功能

c# - 将样式库加载到 WPF 中

c# - 在 C# 测试中从 Json 文件中读取和映射数据

javascript - Ajax json正确显示数据

c# - 拆分大型 JSON 文件的策略

c# - C#中的JSON反序列化错误

c# - 构建正则表达式模式以最终从数据中选择所需的文本

json - 无法使用 Golang 从 App Engine 将有效的 JSON 数据成功发布到远程 URL

c# - 如何使用 NewtonSoft Json.Net 将 Json 字典反序列化为平面类

c# - 运算符 '&&' 不能应用于类型 'int' 和 'bool' 的操作数