我有一个有效的 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/