How to convert json into datatable?

前端 未结 5 722
暗喜
暗喜 2020-11-27 21:17

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. C

5条回答
  •  暖寄归人
    2020-11-27 21:47

    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 UserList = JsonConvert.DeserializeObject(jsonString);
    

    Write following extension method to your project

    public static DataTable ToDataTable(this IList 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();
    

提交回复
热议问题