如何使用Json.Net将简单的JSON字符串解析为DataSet

时间:2013-07-18 02:49:32

标签: json c#-4.0 json.net

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

1 个答案:

答案 0 :(得分:3)

您是否考虑过为数据创建自定义类并反序列化,而不是反序列化为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