2

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?

2
  • 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. Commented May 9, 2015 at 16:45
  • Why convert it to a data table? Why not convert to a POCO? Commented May 9, 2015 at 16:53

1 Answer 1

10

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"}]
Sign up to request clarification or add additional context in comments.

3 Comments

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":"domcno"}, "asdfgqwx.org":{"status":"unknown"} }
@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.
Okay. Here is my full question link

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.