Reputation: 831
I am trying to find a way to both serialize and deserialize a dataset with one datatable to JSON and from JSON back to a dataset / datatable using JSON.NET, however all the samples and examples I have found are only serializing from a dataset or datatable to JSON and never two way. We have a system that deals with XML serialized datasets and datatables that we need to still retain in that format but allow certain UI views to render the data as JSON.
Data can have null values and that's valid.
Any help would be much appreciated.
Example (One way serialization):
http://www.west-wind.com/weblog/posts/2008/Sep/03/DataTable-JSON-Serialization-in-JSONNET-and-JavaScriptSerializer
Upvotes: 0
Views: 7053
Reputation: 48076
The following link is to the source for Newtonsoft.Json.Converters.DataTableConverter.cs which does what you want, it's pretty straight forward and seems like the best route.
Upvotes: 2
Reputation: 25204
This all depends how you want to manage the deserialization. Personally, I like to go with the LINQ-based approach which works in the following way:
// Get the children of the JSON result (This example is from my own code,
// in which case I have one big "result" node which contains a bunch of
// children that I am interested in deserializing.
var jsonChildren = JObject.Parse(response)["results"].Children();
// Now use a LINQ statement to deserialize. For example...
var jsonResults = jsonChildren.Select(x =>
{
new MyObject
{
Prop1 = x["Var1"],
Prop2 = x["Var2"],
}
});
What it all boils down to is that you use the JSON children IEnumerable like you would an array of key value pairs, accessing the necessary descendants using square-bracket syntax. The LINQ just makes things a bit cleaner.
Update
Not sure if this applies to your case, but here is an interesting article on the subject that uses dynamic objects http://www.west-wind.com/weblog/posts/2012/Aug/30/Using-JSONNET-for-dynamic-JSON-parsing
Upvotes: 2