开发者

JSON to DataTable

开发者 https://www.devze.com 2023-02-24 07:48 出处:网络
I am trying to serialize JSON text to DataTable, as in the following. List<Dictionary<string, string>> list =

I am trying to serialize JSON text to DataTable, as in the following.

List<Dictionary<string, string>> list = 
JsonConvert开发者_开发问答.DeserializeObject<List<Dictionary<string, string>>>(jsonText);
DataTable dTable;
dTable = (from p in list select p).CopyToDataTable();

I get the following error. How do I fix it?

ERROR :

Cannot deserialize JSON object into type 
'System.Collections.Generic.List`1[System.Collections.Generic.Dictionary`2
[System.String,System.String]]'.


This works for me:

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


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;
    }


}


Try This

public static DataTable JsonToDataTable(string Json)
        {
            DataTable dt = new DataTable();
            try
            {
                dt = (DataTable)JsonConvert.DeserializeObject(Json, (typeof(DataTable)));
            }
            catch (Exception ex)
            {
                string chk = ex.Message;
                dt = new DataTable();
            }
            return dt;
        }

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号