2

我已经尝试了几乎所有我能想到的尝试使用 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 不会解析。我准备放弃并自己手动解析它。

4

1 回答 1

3

DataSet您是否考虑过为您的数据创建一个自定义类并反序列化为,而不是反序列化为 a ?使用起来可能更简单一些。

例如,如果您定义这样的类:

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. 如果您查看文档中的示例,则数据的结构需要如下所示:

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

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

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

于 2013-07-18T05:09:24.167 回答