12

Does anyone know how to convert a json string into DataTable from asp.net? I came to know about the Deserialize, it needs the class, I just want the datatable as returned. Can anyone tell me how to convert it to datatable?

casperOne
  • 73,706
  • 19
  • 184
  • 253
Abbas
  • 4,948
  • 31
  • 95
  • 161

5 Answers5

22

Assuming that your JSON string is a list of objects, each object will correspond to a row in the DataTable, viz:

    public DataTable DerializeDataTable()
    {
        const string json = @"[{""Name"":""AAA"",""Age"":""22"",""Job"":""PPP""},"
                           + @"{""Name"":""BBB"",""Age"":""25"",""Job"":""QQQ""},"
                           + @"{""Name"":""CCC"",""Age"":""38"",""Job"":""RRR""}]";
        var table = JsonConvert.DeserializeObject<DataTable>(json);
        return table;
    }

This requires the Json.NET framework.

If your JSON structure is different please post it. Best Regards.

Daniel
  • 1,034
  • 1
  • 10
  • 27
Frank
  • 3,029
  • 5
  • 34
  • 43
  • Did you find the solution. I am facing same issue. `Input string was not in a correct format.Couldn't store <6.94127> in Latitude Co lumn. Expected type is Int64`. I am using Newtonsoft.Json.dll. any solution? – Piraba Oct 11 '12 at 07:30
  • 2
    The builtin DataTable doesn't serialize column information, it has to infer the column type from the data. I've created an improved converter here https://github.com/chris-herring/DataTableConverter – Chris Herring Mar 28 '13 at 01:43
10
using Newtonsoft.Json;

string json = "[{"clientID":"1788","projectID":"19"},{"clientID":"1789","projectID":"24"},{"clientID":"1790","projectID":"24"},{"clientID":"1790","projectID":"23"},{"clientID":"1790","projectID":"21"}]";

DataTable tester = (DataTable) JsonConvert.DeserializeObject(json, (typeof(DataTable)));

Code for the above method

public object Deserialize(string jsonText, Type valueType)
{
    try
    {
        Newtonsoft.Json.JsonSerializer json = new Newtonsoft.Json.JsonSerializer();

        json.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;
        json.ObjectCreationHandling = Newtonsoft.Json.ObjectCreationHandling.Replace;
        json.MissingMemberHandling = Newtonsoft.Json.MissingMemberHandling.Ignore;
        json.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;

        StringReader sr = new StringReader(jsonText);

        Newtonsoft.Json.JsonTextReader reader = new JsonTextReader(sr);
        object result = json.Deserialize(reader, valueType);
        reader.Close();
        return result;
    }
    catch (Exception ex)
    {
        throw ex;
    }


}

Deserialize your jsonstring to some class

List<User> UserList = JsonConvert.DeserializeObject<User>(jsonString);

Write following extension method to your project

 public static DataTable ToDataTable<T>(this IList<T> data)
{
    PropertyDescriptorCollection props =
    TypeDescriptor.GetProperties(typeof(T));
    DataTable table = new DataTable();
    for (int i = 0; i < props.Count; i++)
    {
        PropertyDescriptor prop = props[i];
        table.Columns.Add(prop.Name, prop.PropertyType);
    }
    object[] values = new object[props.Count];
    foreach (T item in data)
    {
        for (int i = 0; i < values.Length; i++)
        {
            values[i] = props[i].GetValue(item);
        }
        table.Rows.Add(values);
    }
    return table;
}

Call extension method like

UserList.ToDataTable<User>();
cyboashu
  • 10,196
  • 2
  • 27
  • 46
gourishankar
  • 113
  • 1
  • 4
  • I'm trying to use the above extension method - No Errors on build. But I do get a compilation error : "Compiler Error Message: CS0121: The call is ambiguous between the following methods or properties: 'ExtensionHelpers.ToDataTable<_Default.Jobs>(System.Collections.Generic.IList<_D‌​efault.Jobs>)' and 'ExtensionHelpers.ToDataTable<_Default.Jobs>(System.Collections.Generic.IList<_D‌​efault.Jobs>)'" Do you have any idea what might be causing it? – Lord-David Jun 18 '15 at 07:28
2

This question is sorta outdated, but someone may be looking for answers, so here it goes. It didn't work with old JSON.NET, but today I upgraded to latest version and viola! It works great.

Have serialized a DataTable into Json back and forth, zero issues! This is an awesome new feature.

Hope it helps others as well. Cheers.

coffekid
  • 621
  • 2
  • 10
  • 25
1

I am not sure which JSON library you are using, but you might want to take a look at JSON.NET as there is a converter object type in there called this:

 Newtonsoft.Json.Converters.DataTableConverter
    // Summary:
    //     Converts a System.Data.DataTable to and from JSON.

I have not used this functionality before but you could have a go with it.

James Roland
  • 8,183
  • 4
  • 30
  • 16
0

It´s simple.

If you are in framework 2.0, you must import json.net (http://json.codeplex.com/) in your project, if your framework is superior, it has json.

The code in vb.net framework 2.0:

Dim Table DataTable

Table = Json.JsonConvert.DeserializeObject(Of DataTable)(Json_string)

That´s all.

AAP
  • 235
  • 1
  • 3
  • 9
  • Be carefull json.net (http://json.codeplex.com/), doesn´t respect table.tablename and primary keys. You must assing it after convert the db. – AAP Mar 02 '12 at 20:14