How to convert a JObject to System.Data.DataSet? Or how to deserialize json to dataset?

If that is the full format of the json you get back, here are two ways to do that:
There are more :slight_smile:

Way 1:
That json (as you showed it) is a dictionary. Dictionary<string, object>
A table is pretty much just a list of exact matching dictionaries: List<Dictionary<string, object>>
so…

string json ="{\"ModelFullPath\": \"100000/100007.SLDPRT\", \"DrawingFullPath\": \"100000/100007.SLDDRW\"}";

DataSet dataSet = new DataSet();

Dictionary<string, object> dictionary = JsonConvert.DeserializeObject<Dictionary<string, object>>(json);

List<Dictionary<string, object>> listOfDictionary = new List<Dictionary<string, object>>();

listOfDictionary.Add(dictionary);

DataTable dataTable = JsonConvert.DeserializeObject<DataTable>(JsonConvert.SerializeObject(listOfDictionary));
dataTable.TableName = "ILikeThisTableName";

dataSet.Tables.Add(dataTable);

Console.WriteLine(JsonConvert.SerializeObject(dataSet, Formatting.Indented));

.

Or you can totally cheat and make a template of sorts and do this:
Way2:

string json ="{\"ModelFullPath\": \"100000/100007.SLDPRT\", \"DrawingFullPath\": \"100000/100007.SLDDRW\"}";

string dataSetTemplate = $"{{\"IlikeThisTableName\": [{json}]}}";

DataSet dataSet = JsonConvert.DeserializeObject<DataSet>(dataSetTemplate);

Console.WriteLine(JsonConvert.SerializeObject(dataSet, Formatting.Indented));

.

Output for both is exactly the same:

{
  "IlikeThisTableName": [
    {
      "ModelFullPath": "100000/100007.SLDPRT",
      "DrawingFullPath": "100000/100007.SLDDRW"
    }
  ]
}
1 Like