none
How To Convert JSON Data to DataTable in .NET 2.0

    Question

  • can anybody tell me how i can convert json data into datatable in .c#2.0. i have  seen lots of example using json.net but it work in .NET 3.5  onwards. if anybody have any idea please tell me
    • Edited by arup08 Monday, February 11, 2013 11:00 AM
    Monday, February 11, 2013 10:52 AM

Answers

  • Hi,

    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>();

    Happy Coding.

    Thanks.


    Knight Data Access Layer - .NET ORM, LINQ Provider, and more https://www.kellermansoftware.com/p-47-net-data-access-layer.aspx

    Monday, February 11, 2013 5:03 PM

All replies

  • Take a look at Json.NET. It supports also .Net 2.0.
    Monday, February 11, 2013 1:32 PM
  • Hi,

    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>();

    Happy Coding.

    Thanks.


    Knight Data Access Layer - .NET ORM, LINQ Provider, and more https://www.kellermansoftware.com/p-47-net-data-access-layer.aspx

    Monday, February 11, 2013 5:03 PM
  • http://stackoverflow.com/questions/11981282/how-to-convert-json-to-datatable-in-c-sharp

    thanks and regard love4csharp

    Monday, February 11, 2013 6:48 PM