Json.net如何支持DataSet DataTable.

http://www.cnblogs.com/usharei/archive/2012/04/20/2458858.html

I've been thinking about replacing the JSON serializer in my internal codebase for some time and finally put a little effort into allowingJSON.NETfromJames Newton Kingto be plugged into my Ajax framework as a replaceable engine. My own parser has served me well,but JSON.NET is a much cleaner design and more flexible especially when dealing with extensibility. There are also a few nice features like the ability to pretty-format the generated JSON for debugging purposes which is immensely helpful when sending data to the client during development.

Although I'm keeping my original parser class (including original basic functionality) JSON.NET can now be optionally plugged in. So why not just replace the parser altogether? As it turns out I've been experimenting with different JSON serializer/deserializers and being able to keep a 'high level' wrapper object into which each of these parsers can be plugged into has been a great time saver as the interface that various application components use doesn't change one bit which is nice indeed.

Anyway,here's the basic code to provide JSON encoding and deserialization in a simple wrapper functions:

public string Serialize(object value)
{
    Type type = value.GetType();

    Newtonsoft.Json.JsonSerializer json = new Newtonsoft.Json.JsonSerializer();

    json.NullValueHandling = NullValueHandling.Ignore;
    
    json.ObjectCreationHandling = Newtonsoft.Json.ObjectCreationHandling.Replace;
    json.MissingMemberHandling = Newtonsoft.Json.MissingMemberHandling.Ignore;
    json.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;

    if (type == typeof(DataRow))            
        json.Converters.Add(new DataRowConverter());
    else if(type == typeof(DataTable))
        json.Converters.Add(new DataTableConverter());
    else if (type == typeof(DataSet))
        json.Converters.Add(new DataSetConverter());
    
    StringWriter sw = new StringWriter();
    Newtonsoft.Json.JsonTextWriter writer = new JsonTextWriter(sw);
    if (this.FormatJsonOutput)
        writer.Formatting = Formatting.Indented;
    else
        writer.Formatting = Formatting.None;

    writer.QuoteChar = '"';
    json.Serialize(writer,value);
    
    string output = sw.ToString();
    writer.Close(); 
    sw.Close();
    
    return output;
}

public object Deserialize(string jsonText,Type valueType)
{
    Newtonsoft.Json.JsonSerializer json = new Newtonsoft.Json.JsonSerializer();
    
    json.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;
    json.ObjectCreationHandling = Newtonsoft.Json.ObjectCreationHandling.Replace;
    json.MissingMemberHandling = Newtonsoft.Json.MissingMemberHandling.Ignore;
    json.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;

    StringReader sr = new StringReader(jsonText);
    Newtonsoft.Json.JsonTextReader reader = new JsonTextReader(sr);            
    object result = json.Deserialize(reader,valueType);
    reader.Close();

    return result;
}

One of the nice things about the JSON.NET parser is that there are a tons of configuration options that allow you to customize how JSON parsing occurs. You can see some of the options above for things like null value handling and managing how deep recursive loops should be handled for example.

JSON.NET also has a simplifiedJavaScriptConvert classthat has much simpler serialization and deserialization methods,but this wrapper doesn't have access to the configuration options,so creating a custom wrapper that does exactly what I need certainly helps. As you can see above the parser has a ton of control over how many parsing aspects are handled which is really cool.

The really nice thing though - and the thing that really is missing in my parser - is extensibility. You can create custom Converters that can be plugged into the parsing pipeline to serialize and optionally deserialize custom types. Any JSON parser is likely to do well with most common types,but there may also be custom types or structures that are not supported or not well supported. For example,the ADO.NET objects,or a less obvious problem of how IDictionary types are handled (JSON.NET only supports string keys and then only those that result in valid JavaScript property/map names).

Luckily you can create your own converters,which is a common way of extensibility. The ASP.NET JavaScriptSerializer also supports extension via Converters. So,my immediate need before I could use the JSON.NET parser for a couple of old apps was to create a parser that can serialize JSON from Datatables.

Here's are a few converters that can create DataSet/DataTable and DataRow JSON with JSON.NET and turns them into simple value arrays (ie Dataset.Tables[].Rows[]). Note the converters are only for serialization not deserialization:

/// <summary>
/// Converts a <see cref="DataRow"/> object to and from JSON.
/// </summary>
public class DataRowConverter : JsonConverter
{
    /// <summary>
    /// Writes the JSON representation of the object.
    /// </summary>
    /// <param name="writer">The <see cref="JsonWriter"/> to write to.</param>
    /// <param name="value">The value.</param>
    public override void WriteJson(JsonWriter writer,object dataRow)
    {
        DataRow row = dataRow as DataRow;

        // *** HACK: need to use root serializer to write the column value
        //     should be fixed in next ver of JSON.NET with writer.Serialize(object)
        JsonSerializer ser = new JsonSerializer();                        

        writer.WriteStartObject();
        foreach (DataColumn column in row.Table.Columns)
        {
            writer.WritePropertyName(column.ColumnName);
            ser.Serialize(writer,row[column]);
        }
        writer.WriteEndObject();
    }

    /// <summary>
    /// Determines whether this instance can convert the specified value type.
    /// </summary>
    /// <param name="valueType">Type of the value.</param>
    /// <returns>
    ///     <c>true</c> if this instance can convert the specified value type; otherwise,<c>false</c>.
    /// </returns>
    public override bool CanConvert(Type valueType)
    {
        return typeof(DataRow).IsAssignableFrom(valueType);
    }

    /// <summary>
    /// Reads the JSON representation of the object.
    /// </summary>
    /// <param name="reader">The <see cref="JsonReader"/> to read from.</param>
    /// <param name="objectType">Type of the object.</param>
    /// <returns>The object value.</returns>
    public override object ReadJson(JsonReader reader,Type objectType)
    {
        throw new NotImplementedException();
    }
}


/// <summary>
/// Converts a DataTable to JSON. Note no support for deserialization
/// </summary>
public class DataTableConverter : JsonConverter
{
    /// <summary>
    /// Writes the JSON representation of the object.
    /// </summary>
    /// <param name="writer">The <see cref="JsonWriter"/> to write to.</param>
    /// <param name="value">The value.</param>
    public override void WriteJson(JsonWriter writer,object dataTable)
    {
        DataTable table = dataTable as DataTable;
        DataRowConverter converter = new DataRowConverter();

        writer.WriteStartObject();

        writer.WritePropertyName("Rows");
        writer.WriteStartArray();
        
        foreach (DataRow row in table.Rows)
        {
            converter.WriteJson(writer,row);
        }

        writer.WriteEndArray();
        writer.WriteEndObject();
    }

    /// <summary>
    /// Determines whether this instance can convert the specified value type.
    /// </summary>
    /// <param name="valueType">Type of the value.</param>
    /// <returns>
    ///     <c>true</c> if this instance can convert the specified value type; otherwise,<c>false</c>.
    /// </returns>
    public override bool CanConvert(Type valueType)
    {
        return typeof(DataTable).IsAssignableFrom(valueType);
    }

    /// <summary>
    /// Reads the JSON representation of the object.
    /// </summary>
    /// <param name="reader">The <see cref="JsonReader"/> to read from.</param>
    /// <param name="objectType">Type of the object.</param>
    /// <returns>The object value.</returns>
    public override object ReadJson(JsonReader reader,Type objectType)
    {
        throw new NotImplementedException();
    }
}

/// <summary>
/// Converts a <see cref="DataSet"/> object to JSON. No support for reading.
/// </summary>
public class DataSetConverter : JsonConverter
{
    /// <summary>
    /// Writes the JSON representation of the object.
    /// </summary>
    /// <param name="writer">The <see cref="JsonWriter"/> to write to.</param>
    /// <param name="value">The value.</param>
    public override void WriteJson(JsonWriter writer,object dataset)
    {
        DataSet dataSet = dataset as DataSet;
        
        DataTableConverter converter = new DataTableConverter();

        writer.WriteStartObject();

        writer.WritePropertyName("Tables");
        writer.WriteStartArray();

        foreach (DataTable table in dataSet.Tables)
        {
            converter.WriteJson(writer,table);
        }
        writer.WriteEndArray();
        writer.WriteEndObject();
    }

    /// <summary>
    /// Determines whether this instance can convert the specified value type.
    /// </summary>
    /// <param name="valueType">Type of the value.</param>
    /// <returns>
    ///     <c>true</c> if this instance can convert the specified value type; otherwise,<c>false</c>.
    /// </returns>
    public override bool CanConvert(Type valueType)
    {
        return typeof(DataSet).IsAssignableFrom(valueType);
    }

    /// <summary>
    /// Reads the JSON representation of the object.
    /// </summary>
    /// <param name="reader">The <see cref="JsonReader"/> to read from.</param>
    /// <param name="objectType">Type of the object.</param>
    /// <returns>The object value.</returns>
    public override object ReadJson(JsonReader reader,Type objectType)
    {
        throw new NotImplementedException();
    }
}

Maybe somebody else will find this useful as well. The serialization is one way only because I personally don't have any need for two-way and deserialization of these objects is tricky because deserialization requires a type to match properties to values in the parsed JSON and well these ADO structures don't have any type format.

Anyway JSON.NET is really nice because it's highly configurable and actively developed. It's also open code so you can look through it and see how its done and tweak if necessary. One thing though - it appears it is a bit slower than other solutions. I've found JSON.NET 2.0 to be more than twice as slow as other solutions,and JSON.NET 3.0 as much as 6 to 7 times slower in some informal iteration tests built into my test suite (I noticed this because tests were slowing down drastically on the perf loop). While processing times are still very small (7 seconds for 10,000 serializations w/ JN 3.0) it still rankles a bit when its considerably slower than other solutions.

DataSet/DataTable/DataRow Serialization in JavaScriptSerializer

The stock JavaScriptSerializer that ships with System.Web.Extensions as part of .NET 3.5 also doesn't directly support ADO.NET objects. Some time ago there was a Converter provided in the Futures package (might still be but I haven't checked) but I never actually used it because the Futures assembly is just too much in flux and you never know what sticks around and will get axed.

Luckily it's also pretty easy to create custom converters for JavaScriptSerializer and so it's easy to create DataSet/Table/Row converters that you can add to your own apps without having to rely on the futures DLL. Here's that same implementation for the JavaScriptSerializer:

internal class WebExtensionsJavaScriptSerializer : JSONSerializerBase,IJSONSerializer
{
    public WebExtensionsJavaScriptSerializer(JSONSerializer serializer) : base(serializer)
    {}
  
    public string Serialize(object value)
    {
        JavaScriptSerializer ser = new JavaScriptSerializer();

        List<JavaScriptConverter> converters = new List<JavaScriptConverter>();

        if (value != null)
        {
            Type type = value.GetType();
            if (type == typeof(DataTable) || type == typeof(DataRow) || type == typeof(DataSet))
            {
                converters.Add(new WebExtensionsDataRowConverter());
                converters.Add(new WebExtensionsDataTableConverter());
                converters.Add(new WebExtensionsDataSetConverter());
            }

            if (converters.Count > 0)
                ser.RegisterConverters(converters);
        }
        
        return = ser.Serialize(value);
    }
    public object Deserialize(string jsonText,Type valueType)
    {
        // *** Have to use Reflection with a 'dynamic' non constant type instance
        JavaScriptSerializer ser = new JavaScriptSerializer();

        
        object result = ser.GetType()
                           .GetMethod("Deserialize")
                           .MakeGenericMethod(valueType)
                          .Invoke(ser,new object[1] { jsonText });
        return result;
    }
}



internal class WebExtensionsDataTableConverter : JavaScriptConverter
{
    public override IEnumerable<Type> SupportedTypes
    {
        get { return new Type[] {typeof (DataTable)}; }
    }

    public override object Deserialize(IDictionary<string,object> dictionary,Type type,JavaScriptSerializer serializer)
    {
        throw new NotImplementedException();
    }
 

    public override IDictionary<string,object> Serialize(object obj,JavaScriptSerializer serializer)
    {
        DataTable table = obj as DataTable;

        // *** result 'object'
        Dictionary<string,object> result = new Dictionary<string,object>();

        if (table != null)
        {
            // *** We'll represent rows as an array/listType
            List<object> rows = new List<object>();

            foreach (DataRow row in table.Rows)
            {
                rows.Add(row);  // Rely on DataRowConverter to handle
            }
            result["Rows"] = rows;

            return result;
        }

        return new Dictionary<string,object>();
    }
}

internal class WebExtensionsDataRowConverter : JavaScriptConverter
{
    public override IEnumerable<Type> SupportedTypes
    {
        get { return new Type[] { typeof(DataRow) }; }
    }

    public override object Deserialize(IDictionary<string,JavaScriptSerializer serializer)
    {
        throw new NotImplementedException();
    }

    public override IDictionary<string,JavaScriptSerializer serializer)
    {
        DataRow dataRow = obj as DataRow;
        Dictionary<string,object> propValues = new Dictionary<string,object>();                    

        if (dataRow != null)
        {
            foreach (DataColumn dc in dataRow.Table.Columns)
            {
                propValues.Add( dc.ColumnName,dataRow[dc]);
            }
        }

        return propValues;
    }
}

internal class WebExtensionsDataSetConverter : JavaScriptConverter
{
    public override IEnumerable<Type> SupportedTypes
    {
        get { return new Type[] { typeof(DataSet) }; }
    }

    public override object Deserialize(IDictionary<string,JavaScriptSerializer serializer)
    {
        DataSet dataSet = obj as DataSet;
        Dictionary<string,object> tables = new Dictionary<string,object>();

        if (dataSet != null)
        {
            foreach (DataTable dt in dataSet.Tables)
            {
                tables.Add(dt.TableName,dt);
            }
        }

        return tables;
    }
}

Implementing a custom converter involves creating dictionaries of property name and value pairs with the abillity to create nested properties by specifying another dictionary as a value. This approach is makes it pretty easy to create custom serialization formats...

I know I'm not using DataSets much anymore these days but with older code still sitting around that does these converters are coming in handy. Maybe this will prove useful to some of you in a similar situation.

http://www.west-wind.com/weblog/posts/2008/Sep/03/DataTable-JSON-Serialization-in-JSONNET-and-JavaScriptSerializer

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


文章浏览阅读2.4k次。最近要优化cesium里的热力图效果,浏览了网络上的各种方法,发现大多是贴在影像上的。这么做好是好,但是会被自生添加的模型或者其他数据给遮盖。其次是网上的方法大多数是截取成一个矩形。不能自定义的截取自己所需要的。经过尝试,决定修改下cesium heatmap,让他达到我们需要的要求。首先先下载 cesium heatmap包。其中我们可以看到也是通过叠加entity达到添加canvas的方法绘制到地图上。我们先把这一段代码注释} else {} };
文章浏览阅读1.2w次,点赞3次,收藏19次。在 Python中读取 json文件也可以使用 sort ()函数,在这里我介绍一个简单的示例程序: (4)如果我们想将字符串转换为列表形式,只需要添加一个变量来存储需要转换的字符串即可。在上面的代码中,我们创建了一个名为` read`的对象,然后在文件的开头使用`./`关键字来命名该对象,并在文件中定义了一个名为` json`的变量,并在其中定义了一个名为` json`的字段。比如,我们可以使用 read方法读取 json文件中的内容,然后使用 send方法将其发送到 json文件中。_python怎么读取json文件
文章浏览阅读1.4k次。首字母缩略词 API 代表应用程序编程接口,它是一种设备,例如用于使用编程代码发送和检索数据的服务器。最常见的是,该技术用于从源检索数据并将其显示给软件应用程序及其用户。当您访问网页时,API 的工作方式与浏览器相同,信息请求会发送到服务器,如何在 Windows PC 中手动创建系统还原点服务器会做出响应。唯一的区别是服务器响应的数据类型,对于 API,数据是 JSON 类型。JSON 代表 JavaScript Object Notation,它是大多数软件语言中 API 的标准数据表示法。_api是什么 python
文章浏览阅读802次,点赞10次,收藏10次。解决一个JSON反序列化问题-空字符串变为空集合_cannot coerce empty string ("") to element of `java.util.arraylist
文章浏览阅读882次。Unity Json和Xml的序列化和反序列化_unity json反序列化存储换行
文章浏览阅读796次。reader.readAsText(data.file)中data.file的数据格式为。使用FileReader对象读取文件内容,最后将文件内容进行处理使用。_a-upload 同时支持文件和文件夹
文章浏览阅读775次,点赞19次,收藏10次。fastjson是由国内的阿里推出的一种json处理器,由java语言编写,无依赖,不需要引用额外的jar包,能直接运行在jdk环境中,它的解析速度是非常之快的,目前超过了所有json库。提示:以下是引用fastjson的方法,数据未涉及到私密信息。_解析器用fastjson还是jackson
文章浏览阅读940次。【Qt之JSON文件】QJsonDocument、QJsonObject、QJsonArray等类介绍及使用_使用什么方法检查qjsondocument是否为空
文章浏览阅读957次,点赞34次,收藏22次。主要内容原生 ajax重点重点JSON熟悉章节目标掌握原生 ajax掌握jQuery ajax掌握JSON第一节 ajax1. 什么是ajaxAJAX 全称为,表示异步的Java脚本和Xml文件,是一种异步刷新技术。2. 为什么要使用ajaxServlet进行网页的变更往往是通过请求转发或者是重定向来完成,这样的操作更新的是整个网页,如果我们只需要更新网页的局部内容,就需要使用到AJAX来处理了。因为只是更新局部内容,因此,Servlet。
文章浏览阅读1.4k次,点赞45次,收藏13次。主要介绍了JsonFormat与@DateTimeFormat注解实例解析,文中通过示例代码介绍的非常详细,对大家的学习 或者工作具有一定的参考学习价值,需要的朋友可以参考下 这篇文章主要介绍了从数据库获取时间传到前端进行展示的时候,我们有时候可能无法得到一个满意的时间格式的时间日期,在数据库中显 示的是正确的时间格式,获取出来却变成了时间戳,@JsonFormat注解很好的解决了这个问题,我们通过使用 @JsonFormat可以很好的解决:后台到前台时间格式保持一致的问题,
文章浏览阅读1k次。JsonDeserialize:json反序列化注解,作用于setter()方法,将json数据反序列化为java对象。可以理解为用在处理接收的数据上。_jsondeserialize
文章浏览阅读2.7k次。labelme标注的json文件是在数据标注时产生,不能直接应用于模型训练。各大目标检测训练平台或项目框架均有自己的数据格式要求,通常为voc、coco或yolo格式。由于yolov8项目比较火热,故此本博文详细介绍将json格式标注转化为yolo格式的过程及其代码。_labelme json 转 yolo
文章浏览阅读790次,点赞26次,收藏6次。GROUP_CONCAT_UNORDERED(): 与GROUP_CONCAT类似,但不保证结果的顺序。COUNT_DISTINCT_AND_ORDERED(): 计算指定列的不同值的数量,并保持结果的顺序。COUNT_ALL_DISTINCT(): 计算指定列的所有不同值的数量(包括NULL)。AVG_RANGE(): 计算指定列的最大值和最小值之间的差异的平均值。JSON_OBJECT(): 将结果集中的行转换为JSON对象。COUNT_DISTINCT(): 计算指定列的不同值的数量。_mysql json 聚合
文章浏览阅读1.2k次。ajax同步与异步,json-serve的安装与使用,node.js的下载_json-serve 与node版本
文章浏览阅读1.7k次。`.net core`提供了Json处理模块,在命名空间`System.Text.Json`中,下面通过顶级语句,对C#的Json功能进行讲解。_c# json
文章浏览阅读2.8k次。主要介绍了python对于json文件的读写操作内容_python读取json文件
文章浏览阅读770次。然而,有时候在处理包含中文字符的Json数据时会出现乱码的情况。本文将介绍一种解决Json中文乱码问题的常见方法,并提供相应的源代码和描述。而某些情况下,中文字符可能会被错误地编码或解码,导致乱码的出现。通过适当地控制编码和解码过程,我们可以有效地处理包含中文字符的Json数据,避免乱码的发生。通过控制编码和解码过程,我们可以确保Json数据中的中文字符能够正确地传输和解析。为了解决这个问题,我们可以使用C#的System.Text.Encoding类提供的方法进行编码和解码的控制。_c# json 中文编码
文章浏览阅读997次。【代码】【工具】XML和JSON互相转换。_xml 转json
文章浏览阅读1.1k次。json path 提取数据_jsonpath数组取值
文章浏览阅读3w次,点赞35次,收藏36次。本文主要介绍了pandas read_json时ValueError: Expected object or value的解决方案,希望能对学习python的同学们有所帮助。文章目录1. 问题描述2. 解决方案_valueerror: expected object or value