Stanley Ekpunobi Stanley Ekpunobi - 1 month ago 13
ASP.NET (C#) Question

convert json array to datatable asp.net

Please i am very new to json. I have a url which i pass values and the data returned is in json. I need to deserialize the json from this url and then bind it to a list view control in asp.net. This is what the json data looks like.

{"records":[{"record":{"Ch_ID":"27","User_id":"1","Ch_Name":"test1","Ch_Description":"test1description","Ch_Starttime":""}},{"record":{"Ch_ID":"29","User_id":"1","Ch_Name":"w","Ch_Description":"ww","Ch_Starttime":"12"}},{"record":{"Ch_ID":"30","User_id":"1","Ch_Name":"qq","Ch_Description":"qqqdescription","Ch_Starttime":"1222"}},{"record":{"Ch_ID":"31","User_id":"1","Ch_Name":"v","Ch_Description":"vv","Ch_Starttime":"1"}},{"record":{"Ch_ID":"32","User_id":"1","Ch_Name":"n","Ch_Description":"nnnn","Ch_Starttime":"111"}}]}


Does anyone have any idea on how I can do this. I have tried out json.net but it is giving me errors.

dbc dbc
Answer

Json.NET does support deserializing a DataTable via its built-in DataTableConverter, however it expects the JSON to be formatted as an array, as follows:

[
  {
    "Ch_ID": "27",
    "User_id": "1",
    // Other fields
  },
  {
    "Ch_ID": "29",
    "User_id": "1",
    // Other fields
  },
  // Other records
]

Your JSON is instead formatted as follows:

{
  "records": [
    {
      "record": {
        "Ch_ID": "27",
        "User_id": "1",
        // Other fields
      }
    },
    {
      "record": {
        "Ch_ID": "29",
        "User_id": "1",
        // Other fields
      }
    },
    // Other records
  ]
}

You can translate your actual JSON into the format required by Json.NET by using a custom JsonConverter:

public class RecordDataTableConverter : Newtonsoft.Json.Converters.DataTableConverter
{
    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        if (reader.TokenType == JsonToken.Null)
            return null;
        if (reader.TokenType == JsonToken.StartObject)
        {
            var token = JToken.Load(reader);
            token = new JArray(token.SelectTokens("records[*].record"));
            using (var subReader = token.CreateReader())
            {
                while (subReader.TokenType == JsonToken.None)
                    subReader.Read();
                return base.ReadJson(subReader, objectType, existingValue, serializer); // Use base class to convert
            }
        }
        else
        {
            return base.ReadJson(reader, objectType, existingValue, serializer);
        }
    }
}

And use it as follows:

var json = GetJson();

var settings = new JsonSerializerSettings
{
    Converters = new[] { new RecordDataTableConverter() },
};

var table = JsonConvert.DeserializeObject<DataTable>(json, settings);

Sample fiddle.

Comments