How to perform serialization and deserialization of datatables to and from JSON

≯℡__Kan透↙ 提交于 2019-12-08 12:21:16

问题


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


回答1:


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.

https://github.com/JamesNK/Newtonsoft.Json/blob/master/Src/Newtonsoft.Json/Converters/DataTableConverter.cs




回答2:


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



来源:https://stackoverflow.com/questions/13165712/how-to-perform-serialization-and-deserialization-of-datatables-to-and-from-json

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!