使用Json.NET从Json字符串反序列化嵌套的DataSet [英] Deserialize a nested DataSet from Json String with Json.NET

查看:105
本文介绍了使用Json.NET从Json字符串反序列化嵌套的DataSet的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用Json.NET从JSON字符串反序列化数据集. Json字符串包含状态,消息和我要使用的表:

I try to deserialize a DataSet from a JSON String with Json.NET. The Json String contents a status, message and the table that I want to use:

{
    "status": "ok",
    "message": "",
    "table": [{
        "column1": "value1",
        "column2": "value2"
    }, {
        "column1": "value3",
        "column2": "value4"
    }]
}

这是我的出处:

    public class RequestResult
    {
        public string status { get; set; }
        public string message { get; set; }
    }

    ...

    var serializer = new JsonSerializer();
    var sr = new StreamReader(response.GetResponseStream()).ReadToEnd();
    var rr = JsonConvert.DeserializeObject<RequestResult>(sr);

    // Without status and message the following works fine like here: 
    // http://www.newtonsoft.com/json/help/html/DeserializeDataSet.htm
    DataSet dataSet = JsonConvert.DeserializeObject<DataSet>(sr);
    gridControlMain.DataSource = dataSet.Tables["table"];

如果我使用不带状态和消息的Json字符串,它可以正常工作,但我需要状态和消息!来自Json.NET的异常消息是: 读取DataTable时出现意外的JSON令牌.应该是StartArray,得到了String.路径状态",第1行,位置14 . 我该如何处理?

If I use the Json String without status and message it works fine, but I need status and message! Exception message from Json.NET is: Unexpected JSON token when reading DataTable. Expected StartArray, got String. Path 'status', line 1, position 14. How can I manage that?

最诚挚的问候

推荐答案

您的代码片段显示了具有三个属性statusmessagetable对象.该对象不能反序列化为DataTable. table属性可以.

Your snippet shows an object with three properties, status, message and table. This object can't be deserialized as a DataTable. The table property can.

您可以将此代码段反序列化为具有两个字符串和一个DataTable属性的类,例如:

You can deserialize this snippet to a class with two string and one DataTable property, eg:

class MyTableUtilClass
{
    public string Status{get;set;}
    public string Message {get;set;}
    public DataTable Table{get;set;}
}


var myUtil=JsonConvert.DeserializeObject<MyTableUtilClass>(jsonText);
DataTable myTable=myUtil.Table;

这篇关于使用Json.NET从Json字符串反序列化嵌套的DataSet的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆