gpt4 book ai didi

json - 如何使用 Json.Net 将简单的 JSON 字符串解析为数据集

转载 作者:行者123 更新时间:2023-12-04 04:49:04 24 4
gpt4 key购买 nike

我已经尝试了几乎所有我能想到的尝试使用 JSON.net 库解析这个 JSON 字符串的方法,但我一直收到一个错误,提示“字符串反序列化后的附加文本”。有没有人对可能出现的问题有任何想法?

这是我拥有的 JSON 字符串:

{"w_vendor":["914115361","914115361","914115361","914115361","914115361","914115361","914115361","914115361","914115361","914115361","914115361","914115361","914115361","914115361","914115361","914115361","914115361","914115361","914115361","914115361","914115361","914115361","914115361","914115361","914115361","914115361","914115361","914115361","914115361","914115361","914115361","914115361","914115361","914115361","914115361","914115361"]}

这是我用来尝试解析它的代码:
var pdfValue = Request["pdfValue"];
string OutputCacheLocation = JsonConvert.SerializeObject(pdfValue);
DataSet dataset = JsonConvert.DeserializeObject<DataSet>(pdfValue);

DataTable datatable = dataset.Tables["table1"];

Response.Write(datatable.Rows.Count);

有没有人看到错误所指的附加文本?我看不到它,而且 JSON 无法解析。我准备放弃并自己手动解析它。

最佳答案

而不是反序列化为 DataSet ,您是否考虑过为您的数据创建一个自定义类并反序列化?使用它可能会更直接一些。

例如,如果你定义一个这样的类:

class Data
{
[JsonProperty(PropertyName="w_vendor")]
public List<string> Values { get; set; }
}

然后你可以像这样反序列化:
string json = @"{""w_vendor"":[""914115361"",""914115361"",""914115361"",""914115361"",""914115361"",""914115361"",""914115361"",""914115361"",""914115361"",""914115361"",""914115361"",""914115361"",""914115361"",""914115361"",""914115361"",""914115361"",""914115361"",""914115361"",""914115361"",""914115361"",""914115361"",""914115361"",""914115361"",""914115361"",""914115361"",""914115361"",""914115361"",""914115361"",""914115361"",""914115361"",""914115361"",""914115361"",""914115361"",""914115361"",""914115361"",""914115361""]}";

var data = JsonConvert.DeserializeObject<Data>(json);

Response.Write(data.Values.Count);

编辑

它没有按照您的方式工作的原因是您的数据不符合反序列化为 DataSet 所需的结构。 .如果你看看 example from the documentation ,数据将需要如下结构:
{
"table1" :
[
{
"column1" : "value1",
"column2" : "value2"
},
{
"column1" : "value3",
"column2" : "value4"
}
],
"table2" :
[
{
"column1" : "value1",
"column2" : "value2"
},
{
"column1" : "value3",
"column2" : "value4"
}
]
}

具体来说,外部对象包含表示表格的属性。属性名称对应于表的名称,值是对象数组,其中每个对象代表表中的一行。对象的属性对应于列名,它们的值是行数据。

在您的数据中,外部对象包含一个属性,其值是一个简单字符串数组,而不是对象。所以这不能变成表,因为 JSON.NET 无法确定列名。此外,您的数据表的名称应该是 w_vendor ,不是 table1 .

关于json - 如何使用 Json.Net 将简单的 JSON 字符串解析为数据集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17713690/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com