Search code examples
c#asp.net.netjson.net

Convert Json string to DataTable


I am trying to Convert Json to DataTable. I found success when converting jsonArray to DataTable. However when converting a json string(below):

var r = {'ASSOCIATION_ID':61.0,'DESCRIPTION':'fssESTf64 - false','ACTIVE':true,'MODEL_TYPE':'0','SEARCH_TYPE':'false','CREATED_BY':'1090323','CREATED_DATE':'2015-09-17T14:41:20','LAST_UPDATED_BY':'1090323','LAST_UPDATED_DATE':'2016-02-26T15:55:54'}

I get an error as {"Unexpected JSON token when reading DataTable. Expected StartArray, got StartObject. Path '', line 1, position 1."}

My code is simple:

DataTable a = JsonConvert.DeserializeObject<DataTable>(r);

Please assist.


Solution

  • Your root JSON container is an object (an unordered collection of comma-separated key/value pairs surrounded by braces - { and }). Json.NET serializes a DataTable as an array of objects (an ordered collection of comma-separated tokens surrounded by square brackets [ and ]), with one array entry for each row, as is shown in Serialize a DataSet. I.e. the following can be deserialized as a data table:

    [
      {
        "ASSOCIATION_ID": 61.0,
        "DESCRIPTION": "fssESTf64 - false",
        "ACTIVE": true,
        "MODEL_TYPE": "0",
        "SEARCH_TYPE": "false",
        "CREATED_BY": "1090323",
        "CREATED_DATE": "2015-09-17T14:41:20",
        "LAST_UPDATED_BY": "1090323",
        "LAST_UPDATED_DATE": "2016-02-26T15:55:54"
      }
    ]
    

    Thus your JSON cannot be mapped automatically to a DataTable by Json.NET.

    If you want, you could deserialize your JSON object as a DataTable with one row. To do that, load it into an intermediate JToken, check if it's an object instead of an array, and if so, wrap it in an array, then deserialize:

    var token = JToken.Parse(r);
    
    if (token.Type == JTokenType.Object)
        token = new JArray(token);
    
    var a = token.ToObject<DataTable>();