Deserialize a nested DataSet from Json String with Json.NET

笑着哭i 提交于 2019-12-25 06:09:01

问题


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"
    }]
}

Here my source:

    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"];

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?

Best regards


回答1:


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.

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;


来源:https://stackoverflow.com/questions/42089414/deserialize-a-nested-dataset-from-json-string-with-json-net

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!