JSON转换类

/// <summary>
        /// 过滤特殊字符
        /// </summary>
        private static string String2Json(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();
        }
/// <summary>
        /// 格式化字符型、日期型、布尔型
        /// </summary>
        private static string StringFormat(string str, Type type)
        {
            if (type == typeof(string))
            {
                str = String2Json(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;
        }
#region List转换成Json
        /// <summary>
        /// List转换成Json
        /// </summary>
        public static string ListToJson<T>(IList<T> list)
        {
            object obj = list[0];
            return ListToJson<T>(list, obj.GetType().Name);
        }

        /// <summary>
        /// List转换成Json
        /// </summary>
        public static string ListToJson<T>(IList<T> list, string jsonName)
        {
            StringBuilder Json = new StringBuilder();
            if (string.IsNullOrEmpty(jsonName)) jsonName = list[0].GetType().Name;
            Json.Append("{\"" + jsonName + "\":[");
            if (list.Count > 0)
            {
                for (int i = 0; i < list.Count; i++)
                {
                    T obj = Activator.CreateInstance<T>();
                    PropertyInfo[] pi = obj.GetType().GetProperties();
                    Json.Append("{");
                    for (int j = 0; j < pi.Length; j++)
                    {
                        Type type = pi[j].GetValue(list[i], null).GetType();
                        Json.Append("\"" + pi[j].Name.ToString() + "\":" + StringFormat(pi[j].GetValue(list[i], null).ToString(), type));

                        if (j < pi.Length - 1)
                        {
                            Json.Append(",");
                        }
                    }
                    Json.Append("}");
                    if (i < list.Count - 1)
                    {
                        Json.Append(",");
                    }
                }
            }
            Json.Append("]}");
            return Json.ToString();
        }
        #endregion

        #region 对象转换为Json
        /// <summary>
        /// 对象转换为Json
        /// </summary>
        /// <param name="jsonObject">对象</param>
        /// <returns>Json字符串</returns>
        public static string ToJson(object jsonObject)
        {
            string jsonString = "{";
            PropertyInfo[] propertyInfo = jsonObject.GetType().GetProperties();
            for (int i = 0; i < propertyInfo.Length; i++)
            {
                object objectValue = propertyInfo[i].GetGetMethod().Invoke(jsonObject, null);
                string value = string.Empty;
                if (objectValue is DateTime || objectValue is Guid || objectValue is TimeSpan)
                {
                    value = "‘" + objectValue.ToString() + "‘";
                }
                else if (objectValue is string)
                {
                    value = "‘" + ToJson(objectValue.ToString()) + "‘";
                }
                else if (objectValue is IEnumerable)
                {
                    value = ToJson((IEnumerable)objectValue);
                }
                else
                {
                    value = ToJson(objectValue.ToString());
                }
                jsonString += "\"" + ToJson(propertyInfo[i].Name) + "\":" + value + ",";
            }
            jsonString.Remove(jsonString.Length - 1, jsonString.Length);
            return jsonString + "}";
        }
        #endregion

        #region 对象集合转换Json
        /// <summary>
        /// 对象集合转换Json
        /// </summary>
        /// <param name="array">集合对象</param>
        /// <returns>Json字符串</returns>
        public static string ToJson(IEnumerable array)
        {
            string jsonString = "[";
            foreach (object item in array)
            {
                jsonString += ToJson(item) + ",";
            }
            jsonString.Remove(jsonString.Length - 1, jsonString.Length);
            return jsonString + "]";
        }
        #endregion

        #region 普通集合转换Json
        /// <summary>
        /// 普通集合转换Json
        /// </summary>
        /// <param name="array">集合对象</param>
        /// <returns>Json字符串</returns>
        public static string ToArrayString(IEnumerable array)
        {
            string jsonString = "[";
            foreach (object item in array)
            {
                jsonString = ToJson(item.ToString()) + ",";
            }
            jsonString.Remove(jsonString.Length - 1, jsonString.Length);
            return jsonString + "]";
        }
        #endregion

        #region  DataSet转换为Json
        /// <summary>
        /// DataSet转换为Json
        /// </summary>
        /// <param name="dataSet">DataSet对象</param>
        /// <returns>Json字符串</returns>
        public static string ToJson(DataSet dataSet)
        {
            string jsonString = "{";
            foreach (DataTable table in dataSet.Tables)
            {
                jsonString += "\"" + table.TableName + "\":" + ToJson(table) + ",";
            }
            jsonString = jsonString.TrimEnd(‘,‘);
            return jsonString + "}";
        }
        #endregion

        #region Datatable转换为Json
        /// <summary>
        /// Datatable转换为Json
        /// </summary>
        /// <param name="table">Datatable对象</param>
        /// <returns>Json字符串</returns>
        public static string ToJson(DataTable dt)
        {
            StringBuilder jsonString = new StringBuilder();
            jsonString.Append("[");
            DataRowCollection drc = dt.Rows;
            for (int i = 0; i < drc.Count; i++)
            {
                jsonString.Append("{");
                for (int j = 0; j < dt.Columns.Count; j++)
                {
                    string strKey = dt.Columns[j].ColumnName;
                    string strValue = drc[i][j].ToString();
                    Type type = dt.Columns[j].DataType;
                    jsonString.Append("\"" + strKey + "\":");
                    strValue = StringFormat(strValue, type);
                    if (j < dt.Columns.Count - 1)
                    {
                        jsonString.Append(strValue + ",");
                    }
                    else
                    {
                        jsonString.Append(strValue);
                    }
                }
                jsonString.Append("},");
            }
            jsonString.Remove(jsonString.Length - 1, 1);
            jsonString.Append("]");
            return jsonString.ToString();
        }

        /// <summary>
        /// DataTable转换为Json
        /// </summary>
        public static string ToJson(DataTable dt, string jsonName)
        {
            StringBuilder Json = new StringBuilder();
            if (string.IsNullOrEmpty(jsonName)) jsonName = dt.TableName;
            Json.Append("{\"" + jsonName + "\":[");
            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("]}");
            return Json.ToString();
        }
        #endregion

        #region DataReader转换为Json
        /// <summary>
        /// DataReader转换为Json
        /// </summary>
        /// <param name="dataReader">DataReader对象</param>
        /// <returns>Json字符串</returns>
        public static string ToJson(DbDataReader dataReader)
        {
            StringBuilder jsonString = new StringBuilder();
            jsonString.Append("[");
            while (dataReader.Read())
            {
                jsonString.Append("{");
                for (int i = 0; i < dataReader.FieldCount; i++)
                {
                    Type type = dataReader.GetFieldType(i);
                    string strKey = dataReader.GetName(i);
                    string strValue = dataReader[i].ToString();
                    jsonString.Append("\"" + strKey + "\":");
                    strValue = StringFormat(strValue, type);
                    if (i < dataReader.FieldCount - 1)
                    {
                        jsonString.Append(strValue + ",");
                    }
                    else
                    {
                        jsonString.Append(strValue);
                    }
                }
                jsonString.Append("},");
            }
            dataReader.Close();
            jsonString.Remove(jsonString.Length - 1, 1);
            jsonString.Append("]");
            return jsonString.ToString();
        }
        #endregion
/// <summary>
/// json字符串转换为Xml对象
/// </summary>
/// <param name="sJson"></param>
/// <returns></returns>
public static XmlDocument Json2Xml(string sJson)
{
//XmlDictionaryReader reader = JsonReaderWriterFactory.CreateJsonReader(Encoding.UTF8.GetBytes(sJson), XmlDictionaryReaderQuotas.Max);
//XmlDocument doc = new XmlDocument();
//doc.Load(reader);

JavaScriptSerializer oSerializer = new JavaScriptSerializer();
Dictionary<string, object> Dic = (Dictionary<string, object>)oSerializer.DeserializeObject(sJson);
XmlDocument doc = new XmlDocument();
XmlDeclaration xmlDec;
xmlDec = doc.CreateXmlDeclaration("1.0", "gb2312", "yes");
doc.InsertBefore(xmlDec, doc.DocumentElement);
XmlElement nRoot = doc.CreateElement("root");
doc.AppendChild(nRoot);
foreach (KeyValuePair<string, object> item in Dic)
{
XmlElement element = doc.CreateElement(item.Key);
KeyValue2Xml(element, item);
nRoot.AppendChild(element);
}
return doc;
}

private static void KeyValue2Xml(XmlElement node, KeyValuePair<string, object> Source)
{
object kValue = Source.Value;
if (kValue.GetType() == typeof(Dictionary<string, object>))
{
foreach (KeyValuePair<string, object> item in kValue as Dictionary<string, object>)
{
XmlElement element = node.OwnerDocument.CreateElement(item.Key);
KeyValue2Xml(element, item);
node.AppendChild(element);
}
}
else if (kValue.GetType() == typeof(object[]))
{
object[] o = kValue as object[];
for (int i = 0; i < o.Length; i++)
{
XmlElement xitem = node.OwnerDocument.CreateElement("Item");
KeyValuePair<string, object> item = new KeyValuePair<string, object>("Item", o[i]);
KeyValue2Xml(xitem, item);
node.AppendChild(xitem);
}

}
else
{
XmlText text = node.OwnerDocument.CreateTextNode(kValue.ToString());
node.AppendChild(text);
}
}
时间: 2024-10-13 21:06:02

JSON转换类的相关文章

JSON转换类(一)--过滤特殊字符,格式化字符型、日期型、布尔型

/// <summary> /// 过滤特殊字符 /// </summary> private static string String2Json(String s) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < s.Length; i++) { char c = s.ToCharArray()[i]; switch (c) { case '\"': sb.Append("\\\

C# JSON帮助类

using System; using System.Collections.Generic; using System.Text; using System.Data; using System.Reflection; using System.Collections; using System.Data.Common; using System.Web.Script.Serialization; namespace BO.JSON { //JSON转换类 public class Conve

JSON帮助类

using System; using System.Collections; using System.Collections.Generic; using System.Data; using System.Linq; using System.Reflection; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; using System.Runtime.Seria

常用的java类型转json的转换类

公司不准引入json-lib-2.x.jar所以只好自己写了一个基本类型的object转json的类,然后支持8种基本类型和javabean,list,map,array,使用putJSON方法,key值随便写,value是要转换的对象. JsonObjectConvert.java: package com.pz.util; import java.lang.reflect.Field; import java.util.Date; import java.util.Iterator; imp

Json与类对象转换

Json在js,jquery中可以直接使用,比如下串: { "from":"en" ,"to":"zh" ,"trans_result": [ {"src":"today","dst":"\u4eca\u5929"} ] } 可以直接使用data.from即可获取到"en". 但是在c#中不可以.要获取值,有

Json转换工具类(基于google的Gson和阿里的fastjson)

在项目之中我们经常会涉及到字符串和各种对象的转换,为此特地整理了一下常用的转换方法 一.基于com.google.code.gson封装的json转换工具类 1. 在pom.xml文件里面引入gson的依赖 <dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.8.3</version> &

atitit.XML类库选型及object 对象bean 跟json转换方案

atitit.XML类库选型及object 对象bean 跟json转换方案 1. XML类库可以分成2大类.标准的.这些类库通常接口和实现都是分开的 1 2. 常见的xml方面的方法 2 2.1. xml解析 2 2.2. bean与xml互相转换 2 2.3. json与xml的互相转换 2 3. 大名鼎鼎的 DOM  绿色环保的 SAX 默默无闻的 Digester 2 3.1. 默默无闻的 Digester:XML 的 JavaBean 化 2 4. Digester 解析 XML 3

JSON转换

JSON简介 JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式.它易于编程人员阅读和编写,同时也易于机器解析和生成.它基于JavaScript Programming Language, Standard ECMA-262 3rd Edition – December 1999的一个子集.JSON采用完全独立于语言的文本格式,但是也使用了类似于C语言家族的习惯(包括C, C++, C#, Java, JavaScript, Perl, Python等)

XML,Object,Json转换之浅析Xstream的使用

XML,Object,Json转换之浅析Xstream的使用 请尊重他人的劳动成果,转载请注明出处:XML,Object,Json转换之浅析Xstream的使用 XStream的是一个简单的库,主要用于Java对象和XML之间的转换.但XStream也内置了对Json的支持. 1.Xstream的特点: 这里直接引用Xstream官方的叙述: 灵活易用:在更高的层次上提供了简单.灵活.易用的统一接口,用户无需了解项目的底层细节 无需映射:大多数对象都可以在无需映射的情况下进行序列化与反序列化的操