问题
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