Converting Json object to DataTable

18,388

Use something like:

JArray array = new JArray();

{
    JObject row = new JObject();

    row.Add("Name", "Blue Umbrella");
    row.Add("Price", 100);

    array.Add(row);
}

{
    JObject row = new JObject();

    row.Add("Name", "Green Umbrella");
    row.Add("Price", 200);

    array.Add(row);
}

DataTable dt = JsonConvert.DeserializeObject<DataTable>(array.ToString());

The "container" must be a JArray.

The next time you have a similar problem, as suggested by @Dr. Wily's, simply try serializing something:

var dt = new DataTable();
dt.Columns.Add("Name");
dt.Columns.Add("Price");

var row = dt.NewRow();
row["Name"] = "Blue Umbrella";
row["Price"] = 100;
dt.Rows.Add(row);

row = dt.NewRow();
row["Name"] = "Green Umbrella";
row["Price"] = 200;
dt.Rows.Add(row);

string serialized = JsonConvert.SerializeObject(dt);

and look at its format:

[{"Name":"Blue Umbrella","Price":"100"},{"Name":"Green Umbrella","Price":"200"}]
Share:
18,388

Related videos on Youtube

Guerrilla
Author by

Guerrilla

Updated on June 04, 2022

Comments

  • Guerrilla
    Guerrilla almost 2 years

    In a few posts here and also on other forums I have found this code quoted for turning a Json object into a DataTable:

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

    I can't get this to work. It always throws a JsonSerializationException. Am I missing something?

    This is simple example to show error:

    JObject query = new JObject();
    JObject results = new JObject();
    
    results.Add("Name", "Blue Umbrella");
    results.Add("Price", 100);
    
    query.Add("results", results);
    
    DataTable dt = (DataTable)JsonConvert.DeserializeObject(query.ToString(), (typeof(DataTable)));
    

    What did I do wrong?

    • Dr. Wily's Apprentice
      Dr. Wily's Apprentice almost 9 years
      I'd take a look at what the string value is that is produced by query.ToString() and compare that with the other examples that you've seen.
    • mason
      mason almost 9 years
      Why convert it to a data table? Why not convert to a POCO?
  • user3786581
    user3786581 about 8 years
    How to change this json string into Datatable C# { "apple.com":{"status":"regthroughothers","classkey":"domcno"‌​}, "asdfgqwx.com":{"status":"available","classkey":"domcno"}, "microsoft.org":{"status":"unknown"}, "apple.org":{"status":"unknown"}, "microsoft.com":{"status":"regthroughothers","classkey":"dom‌​cno"}, "asdfgqwx.org":{"status":"unknown"} }
  • xanatos
    xanatos about 8 years
    @user3786581 I don't think you can: the key name canges, "apple.com" becomes "asdfgqwx.com" becomes "microsoft.com" It is more a Dictionary<string, MyStatusClass>. The question is complex enough that you should ask a full question.
  • user3786581
    user3786581 about 8 years
    Okay. Here is my full question link