C#中Json数据转换

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/xiaoYong_520/article/details/76515958

C#编程,Json数据转换。VS2013,.net4.5,win7平台开发。

下面是一个Json数据转换的工具类。

using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Reflection;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Web.Script.Serialization;

namespace JR_Common
{
    /// <summary>
    /// JSON转换工具类
    /// </summary>
    public class JSONHelper
    {

        /// <summary>
        /// <para>方法说明:</para>
        /// <para>--> 将一个可序列化对象转为json字符串</para>
        /// <para>--> 在调用该方法时须指明传入参数t的参数类型</para>
        /// <para>参数:</para>
        /// <para>--> t:需要转换的对象</para>
        /// <para>--> encoding:编码方式,一般用UTF-8</para>
        /// <para>返回值:</para>
        /// <para>--> json字符串</para>
        /// <para>注:该方法只能用于可序列化对象(如:List)的转换;而字典对象(如:Dictionary)不能使用该方法转换</para>
        /// </summary>
        public static string ObjectToJson<T>(T t, Encoding encoding)
        {
            string jsonString = null;

            DataContractJsonSerializer serializer = null;
            MemoryStream ms = null;
            try
            {
                ms = new MemoryStream();
                serializer = new DataContractJsonSerializer(typeof(T));
                serializer.WriteObject(ms, t);
                jsonString = encoding.GetString(ms.ToArray());
            }
            catch (Exception ex)
            {
                jsonString = null;
                throw ex;
            }
            finally
            {
                ms.Close();
                ms.Dispose();
            }

            return jsonString;
        }


        /// <summary>
        /// <para>方法说明:</para>
        /// <para>--> 从json字符串中反转出一个可序列化对象</para>
        /// <para>--> 在调用该方法时须指明要转化成某一对象的对象类型</para>
        /// <para>参数:</para>
        /// <para>--> jsonStr:json格式的字符串</para>
        /// <para>--> encoding:编码方式,一般用UTF-8</para>
        /// <para>返回值:</para>
        /// <para>--> json字符串</para>
        /// <para>注:该方法只能用于可序列化对象(如:List)的转换;而字典对象(如:Dictionary)不能使用该方法转换</para>
        /// </summary>
        public static T JsonToObject<T>(string json, Encoding encoding)
        {
            T obj = default(T);

            MemoryStream ms = null;
            DataContractJsonSerializer ser = null;
            try
            {
                ms = new MemoryStream(encoding.GetBytes(json));
                ser = new DataContractJsonSerializer(typeof(T));
                obj = (T)ser.ReadObject(ms);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                ms.Close();
                ms.Dispose();
            }

            return obj;
        }


        /// <summary>
        /// <para>方法说明:</para>
        /// <para>--> 将一个DataTable对象转成json字符串</para>
        /// <para>参数:</para>
        /// <para>--> dt:一个非空且有数据的DataTable对象</para>
        /// <para>返回值:</para>
        /// <para>--> json字符串</para>
        /// </summary>
        public static string DataTableToJson(DataTable dt)
        {
            var JsonString = new StringBuilder();
            if (dt != null && dt.Rows.Count > 0)
            {
                JsonString.Append("[");
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    JsonString.Append("{");
                    for (int j = 0; j < dt.Columns.Count; j++)
                    {
                        if (j < dt.Columns.Count - 1)
                        {
                            JsonString.Append("\"" + dt.Columns[j].ColumnName.ToString() + "\":" + "\"" + dt.Rows[i][j].ToString() + "\",");
                        }
                        else if (j == dt.Columns.Count - 1)
                        {
                            JsonString.Append("\"" + dt.Columns[j].ColumnName.ToString() + "\":" + "\"" + dt.Rows[i][j].ToString() + "\"");
                        }
                    }
                    if (i == dt.Rows.Count - 1)
                    {
                        JsonString.Append("}");
                    }
                    else
                    {
                        JsonString.Append("},");
                    }
                }
                JsonString.Append("]");
            }
            return JsonString.ToString();
        }


        /// <summary>
        /// <para>方法说明:</para>
        /// <para>--> 把json字符串转成DataTable对象</para>
        /// <para>参数:</para>
        /// <para>--> json:一个规则的json字符串</para>
        /// <para>返回值:</para>
        /// <para>--> DataTable对象</para>
        /// </summary>
        public static DataTable JsonToDataTable(string json)
        {
            DataTable dataTable = new DataTable();  //实例化  
            DataTable result;
            try
            {
                JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
                javaScriptSerializer.MaxJsonLength = Int32.MaxValue; //取得最大数值  
                ArrayList arrayList = javaScriptSerializer.Deserialize<ArrayList>(json);
                if (arrayList.Count > 0)
                {
                    foreach (Dictionary<string, object> dictionary in arrayList)
                    {
                        if (dictionary.Keys.Count == 0)
                        {
                            result = dataTable;
                            return result;
                        }
                        if (dataTable.Columns.Count == 0)
                        {
                            foreach (string current in dictionary.Keys)
                            {
                                dataTable.Columns.Add(current, dictionary[current].GetType());
                            }
                        }
                        DataRow dataRow = dataTable.NewRow();
                        foreach (string current in dictionary.Keys)
                        {
                            dataRow[current] = dictionary[current];
                        }

                        dataTable.Rows.Add(dataRow); //循环添加行到DataTable中  
                    }
                }
            }
            catch
            {
            }
            result = dataTable;
            return result;
        }




    }
}

以上的 DataTableToJson 方法存在不严谨的地方。下面是优化后的结果。

	#region DataTable数据数据对象转Json字符串

        /// <summary>
        /// <para>方法说明:</para>
        /// <para>--> 将一个DataTable对象转成json字符串</para>
        /// <para>参数:</para>
        /// <para>--> dt:一个非空且有数据的DataTable对象</para>
        /// <para>返回值:</para>
        /// <para>--> json字符串</para>
        /// </summary>
        public static string DataTableToJson(DataTable dt)
        {
            StringBuilder json = new StringBuilder();

            //json.Append("{[");
            json.Append("[");
            if (dt.Rows.Count > 0)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    json.Append("{");
                    for (int j = 0; j < dt.Columns.Count; j++)
                    {
                        Type type = dt.Rows[i][j].GetType();
                        json.Append("\"" + dt.Columns[j].ColumnName.ToString() + "\":" + StringFormat(dt.Rows[i][j].ToString(), type));
                        if (j < dt.Columns.Count - 1)
                        {
                            json.Append(",");
                        }
                    }
                    json.Append("}");
                    if (i < dt.Rows.Count - 1)
                    {
                        json.Append(",");
                    }
                }
            }
            //json.Append("]}");
            json.Append("]");

            return json.ToString();
        }

        /// <summary>
        /// 格式化字符型、日期型、布尔型
        /// </summary>
        private static string StringFormat(string str, Type type)
        {
            if (type == typeof(string))
            {
                str = StringToJson(str);
                str = "\"" + str + "\"";
            }
            else if (type == typeof(DateTime))
            {
                str = "\"" + str + "\"";
            }
            else if (type == typeof(bool))
            {
                str = str.ToLower();
            }
            else if (type != typeof(string) && string.IsNullOrEmpty(str))
            {
                str = "\"" + str + "\"";
            }
            return str;
        }

        /// <summary>
        /// 过滤特殊字符
        /// </summary>
        private static string StringToJson(String s)
        {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < s.Length; i++)
            {
                char c = s.ToCharArray()[i];
                switch (c)
                {
                    case '\"':
                        sb.Append("\\\""); break;
                    case '\\':
                        sb.Append("\\\\"); break;
                    case '/':
                        sb.Append("\\/"); break;
                    case '\b':
                        sb.Append("\\b"); break;
                    case '\f':
                        sb.Append("\\f"); break;
                    case '\n':
                        sb.Append("\\n"); break;
                    case '\r':
                        sb.Append("\\r"); break;
                    case '\t':
                        sb.Append("\\t"); break;
                    default:
                        sb.Append(c); break;
                }
            }
            return sb.ToString();
        }


        #endregion
希望给你带来帮助!!!谢谢大家。


没有更多推荐了,返回首页