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"}]
Related videos on Youtube
Author by
Guerrilla
Updated on June 04, 2022Comments
-
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 almost 9 yearsI'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 almost 9 yearsWhy convert it to a data table? Why not convert to a POCO?
-
-
user3786581 about 8 yearsHow 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":"domcno"}, "asdfgqwx.org":{"status":"unknown"} }
-
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 aDictionary<string, MyStatusClass>
. The question is complex enough that you should ask a full question. -
user3786581 about 8 yearsOkay. Here is my full question link