2

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]]'.
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
John Hansen
  • 288
  • 1
  • 3
  • 14
  • 2
    It seems fairly obvious to me that this has nothing to do with DataTables, as the exception is being thrown in the first line. That's what you should be concentrating on. – Jon Skeet Apr 14 '11 at 07:10
  • Kindly check the answer here http://stackoverflow.com/a/35546685/5292650 Its the most easiest one – M.Nabeel Feb 22 '16 at 06:14

3 Answers3

6

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)));
Aaron Bratcher
  • 6,051
  • 2
  • 39
  • 70
1
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;
    }


}
pratik godha
  • 73
  • 1
  • 8
0

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