0

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

12
  • 1
    You are missing quotation marks around status and message variables Commented Feb 7, 2017 at 12:06
  • I've edited my post but that solves not the problem! Commented Feb 7, 2017 at 12:11
  • share your source code which you have currently used Commented Feb 7, 2017 at 12:26
  • There is no such thing as a nested DataSet. In .NET DataSets contain DataTables with relations. What did you try to do? Please post your code. Commented Feb 7, 2017 at 12:29
  • 1
    If eventually you are going to use datatable as the datasource of DataGrid then why do you need to deserialize string to DataSet. You can add a new property of type DataTable in RequestResult and deserialize the string to RequestResult. Commented Feb 7, 2017 at 13:09

1 Answer 1

2

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;
Sign up to request clarification or add additional context in comments.

1 Comment

You made my day :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.