asp.net(c#)快速生成Json格式的数据(JsonHelper)

在目前web开发的应用中,ajax效果被广泛的应用,需要在在客户端和服务器端频繁的传送数据,json格式的数据被javascript天然的支持,具有良好的编程支持和更好的效率。在以前的开发中,都是每次获取数据的时候构造json数据,没有达到重用和封装的目标。最近参考网上的资源,主要是Json.Net和Rick Strahl’s Web Log,写了一个json的帮助类。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using Newtonsoft.Json;
using System.Data;

namespace VeryCodes.Common
{
    /// 
    /// Json处理类
    /// 
    public class JsonHelper
    {
        /// 
        /// 序列化数据为Json数据格式.
        /// 
        /// The value.
        /// 
        public static 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);
            //writer.Formatting = Formatting.Indented;
            writer.Formatting = Formatting.None;

            writer.QuoteChar = '"';
            json.Serialize(writer, value);

            string output = sw.ToString();
            writer.Close();
            sw.Close();

            return output;
        }

        /// 
        /// 反序列化Json数据格式.
        /// 
        /// The json text.
        /// Type of the value.
        /// 
        public static 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;
        }

        /// 
        /// 遍历DataTable的行和列生成Json,可控制性较差
        /// 
        /// 
        /// 
        public static string DataTable2Json(DataTable dt)
        {
            StringBuilder jsonBuilder = new StringBuilder();
            jsonBuilder.Append("{\"");
            jsonBuilder.Append(dt.TableName);
            jsonBuilder.Append("\":[");
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                jsonBuilder.Append("{");
                for (int j = 0; j < dt.Columns.Count; j++)
                {
                    jsonBuilder.Append("\"");
                    jsonBuilder.Append(dt.Columns[j].ColumnName);
                    jsonBuilder.Append("\":\"");
                    jsonBuilder.Append(dt.Rows[i][j].ToString());
                    jsonBuilder.Append("\",");
                }
                jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
                jsonBuilder.Append("},");
            }
            jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
            jsonBuilder.Append("]");
            jsonBuilder.Append("}");
            return jsonBuilder.ToString();
        }

        /// 
        /// 遍历DataTable的行和列生成Json,控制数据列,专门为FlexiGrid提供便捷的数据源生成
        /// 
        /// DataTable对象
        /// Json中的数据列
        /// 
        public static string Json4FlexiGrid(DataTable dt, string cols)
        {
            StringBuilder jsonBuilder = new StringBuilder();
            string[] colarr = cols.Split(',');

            if (dt.Rows.Count > 0)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    jsonBuilder.Append("{");
                    jsonBuilder.Append("\"id\":");
                    jsonBuilder.Append("\"");
                    jsonBuilder.Append(dt.Rows[i]["ID"].ToString());
                    jsonBuilder.Append("\",\"cell\":[");
                    foreach (string col in colarr)
                    {
                        jsonBuilder.Append("\"");
                        jsonBuilder.Append(dt.Rows[i][col].ToString());
                        jsonBuilder.Append("\",");
                    }
                    jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
                    jsonBuilder.Append("]},");
                }
                jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
            }

            return jsonBuilder.ToString();
        }
    }

    /// 
    /// Converts a  object to and from JSON.
    /// 
    public class DataRowConverter : JsonConverter
    {
        /// 
        /// Writes the JSON representation of the object.
        /// 
        /// The  to write to.
        /// The data row.
        /// The JsonSerializer 对象.
        public override void WriteJson(JsonWriter writer, object dataRow, JsonSerializer ser)
        {
            DataRow row = dataRow as DataRow;

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

        /// 
        /// Determines whether this instance can convert the specified value type.
        /// 
        /// Type of the value.
        /// 
        ///     true if this instance can convert the specified value type; otherwise, false.
        /// 
        public override bool CanConvert(Type valueType)
        {
            return typeof(DataRow).IsAssignableFrom(valueType);
        }

        /// 
        /// Reads the JSON representation of the object.
        /// 
        /// The  to read from.
        /// Type of the object.
        /// The object value.
        public override object ReadJson(JsonReader reader, Type objectType, JsonSerializer ser)
        {
            throw new NotImplementedException();
        }
    }

    /// 
    /// Converts a DataTable to JSON. Note no support for deserialization
    /// 
    public class DataTableConverter : JsonConverter
    {
        /// 
        /// Writes the JSON representation of the object.
        /// 
        /// The  to write to.
        /// The data table.
        /// The JsonSerializer Object.
        public override void WriteJson(JsonWriter writer, object dataTable, JsonSerializer ser)
        {
            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, ser);
            }

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

        /// 
        /// Determines whether this instance can convert the specified value type.
        /// 
        /// Type of the value.
        /// 
        ///     true if this instance can convert the specified value type; otherwise, false.
        /// 
        public override bool CanConvert(Type valueType)
        {
            return typeof(DataTable).IsAssignableFrom(valueType);
        }

        /// 
        /// Reads the JSON representation of the object.
        /// 
        /// The  to read from.
        /// Type of the object.
        /// The object value.
        public override object ReadJson(JsonReader reader, Type objectType, JsonSerializer ser)
        {
            throw new NotImplementedException();
        }
    }

    /// 
    /// Converts a  object to JSON. No support for reading.
    /// 
    public class DataSetConverter : JsonConverter
    {
        /// 
        /// Writes the JSON representation of the object.
        /// 
        /// The  to write to.
        /// The dataset.
        /// The JsonSerializer Object.
        public override void WriteJson(JsonWriter writer, object dataset, JsonSerializer ser)
        {
            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, ser);
            }
            writer.WriteEndArray();
            writer.WriteEndObject();
        }

        /// 
        /// Determines whether this instance can convert the specified value type.
        /// 
        /// Type of the value.
        /// 
        ///     true if this instance can convert the specified value type; otherwise, false.
        /// 
        public override bool CanConvert(Type valueType)
        {
            return typeof(DataSet).IsAssignableFrom(valueType);
        }

        /// 
        /// Reads the JSON representation of the object.
        /// 
        /// The  to read from.
        /// Type of the object.
        /// The object value.
        public override object ReadJson(JsonReader reader, Type objectType, JsonSerializer ser)
        {
            throw new NotImplementedException();
        }
    }
}


flexigrid是一个优秀的javascript表格控件,通过Json4FlexiGrid方法,我们可以很方便的为flexigrid提供数据源。

JsonConverter来源于Newtonsoft.Json,这是一个Json的开源项目,点击这里查看项目信息。

你可能感兴趣的:(JavaScript,NET)