对json进行封装

  项目中经常用到对于JSON的各种转换处理,保存一份,免得以后忘了。

using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using System.Data;
using System.Collections;
using CRM.Common.DotNetData;
using System.IO;
using System.Web.Script.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;

namespace CRM.Common.DotNetJson
{
    /// <summary>
    /// 转换Json格式帮助类
    /// </summary>
    public class JsonHelper
    {
        /// <summary>
        /// 泛型接口转Json
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="list"></param>
        /// <returns></returns>
        public static string IListToJson<T>(IList<T> list)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("[");
            foreach (T t in list)
            {
                sb.Append(ObjectToJson(t) + ",");
            }
            string _temp = sb.ToString().TrimEnd(‘,‘);
            _temp += "]";
            return _temp;
        }
        /// <summary>
        /// 泛型接口转Json
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="list"></param>
        /// <param name="ClassName"></param>
        /// <returns>{"rows":[{"c_id":"21bb6911-af52-42a4-9732-24a6e8384411","eav_id":"4a9fe8ca-112a-47c0-b074-229837cfe6e6","e_id":"cfe929e3-accd-4efb-910b-07705077b6d6","ea_id":"","ea_name":"555","eav_value":"555","eav_memo":"","sud":"0"}]}</returns>
        public static string IListToJson<T>(IList<T> list, string ClassName)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("{\"" + ClassName + "\":[");
            foreach (T t in list)
            {
                sb.Append(ObjectToJson(t) + ",");
            }
            string _temp = sb.ToString().TrimEnd(‘,‘);
            _temp += "]}";
            return _temp;
        }
        /// <summary>
        /// 对象转Json
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="t"></param>
        /// <returns>{"SM_ID":"71","SM_Img":"title.gif","SM_Memo":"当前位置:会所服务 ─ 宾客管理 ─ 宾客列表"}</returns>
        public static string ObjectToJson<T>(T t)
        {
            StringBuilder sb = new StringBuilder();
            string json = "";
            if (t != null)
            {
                sb.Append("{");
                PropertyInfo[] properties = t.GetType().GetProperties();
                foreach (PropertyInfo pi in properties)
                {
                    sb.Append("\"" + pi.Name.ToString() + "\"");
                    sb.Append(":");
                    sb.Append("\"" + pi.GetValue(t, null) + "\"");
                    sb.Append(",");
                }
                json = sb.ToString().TrimEnd(‘,‘);
                json += "}";
            }
            return json;
        }
        /// <summary>
        /// 对象转Json(重载)
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="t"></param>
        /// <param name="ClassName"></param>
        /// <returns>{"menu":[{"SM_ID":"71","SM_Img":"title.gif","SM_Memo":"当前位置:会所服务 ─ 宾客管理 ─ 宾客列表"}]}</returns>
        public static string ObjectToJson<T>(T t, string ClassName)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("{\"" + ClassName + "\":[");
            string json = "";
            if (t != null)
            {
                sb.Append("{");
                PropertyInfo[] properties = t.GetType().GetProperties();
                foreach (PropertyInfo pi in properties)
                {
                    sb.Append("\"" + pi.Name.ToString() + "\"");//.ToLower()
                    sb.Append(":");
                    sb.Append("\"" + pi.GetValue(t, null) + "\"");
                    sb.Append(",");
                }
                json = sb.ToString().TrimEnd(‘,‘);
                json += "}]}";
            }
            return json;
        }
        /// <summary>
        /// List转成json
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="jsonName"></param>
        /// <param name="IL"></param>
        /// <returns></returns>
        public static string ObjectToJson<T>(IList<T> IL, string jsonName)
        {
            StringBuilder Json = new StringBuilder();
            Json.Append("{\"" + jsonName + "\":[");
            if (IL.Count > 0)
            {
                for (int i = 0; i < IL.Count; i++)
                {
                    T obj = Activator.CreateInstance<T>();
                    Type type = obj.GetType();
                    PropertyInfo[] pis = type.GetProperties();
                    Json.Append("{");
                    for (int j = 0; j < pis.Length; j++)
                    {
                        Json.Append("\"" + pis[j].Name.ToString() + "\":\"" + pis[j].GetValue(IL[i], null) + "\"");
                        if (j < pis.Length - 1)
                        {
                            Json.Append(",");
                        }
                    }
                    Json.Append("}");
                    if (i < IL.Count - 1)
                    {
                        Json.Append(",");
                    }
                }
            }
            Json.Append("]}");
            return Json.ToString();
        }

        /// <summary>
        /// 将数组转换为JSON格式的字符串
        /// </summary>
        /// <typeparam name="T">数据类型,如string,int ...</typeparam>
        /// <param name="list">泛型list</param>
        /// <param name="propertyname">JSON的类名</param>
        /// <returns></returns>
        public static string ArrayToJson<T>(List<T> list, string propertyname)
        {
            StringBuilder sb = new StringBuilder();
            if (list.Count > 0)
            {
                sb.Append("[{\"");
                sb.Append(propertyname);
                sb.Append("\":[");
                foreach (T t in list)
                {
                    sb.Append("\"");
                    sb.Append(t.ToString());
                    sb.Append("\",");
                }
                string _temp = sb.ToString();
                _temp = _temp.TrimEnd(‘,‘);
                _temp += "]}]";
                return _temp;
            }
            else
                return "";
        }

        /// <summary>
        /// DataTable转Json
        /// </summary>
        /// <param name="dt">table数据集</param>
        /// <param name="dtName">json名</param>
        /// <returns></returns>
        public static string DataTableToJson(DataTable dt, string dtName)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("{\"");
            sb.Append(dtName);
            sb.Append("\":[");
            if (DataTableHelper.IsExistRows(dt))
            {
                foreach (DataRow dr in dt.Rows)
                {
                    sb.Append("{");
                    foreach (DataColumn dc in dr.Table.Columns)
                    {
                        sb.Append("\"");
                        sb.Append(dc.ColumnName);
                        sb.Append("\":\"");
                        if (dr[dc] != null && dr[dc] != DBNull.Value && dr[dc].ToString() != "")
                            sb.Append(dr[dc]).Replace("\\", "/");
                        else
                            sb.Append("");
                        sb.Append("\",");
                    }
                    sb = sb.Remove(sb.Length - 1, 1);
                    sb.Append("},");
                }
                sb = sb.Remove(sb.Length - 1, 1);
            }
            sb.Append("]}");
            return JsonCharFilter(sb.ToString());
        } 

        /// <summary>
        /// DataTable转Json
        /// </summary>
        /// <param name="dt">table数据集</param>
        /// <param name="dtName">json名</param>
        /// <returns></returns>
        public static string DataTableToJson(DataTable dt)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("[");
            if (DataTableHelper.IsExistRows(dt))
            {
                foreach (DataRow dr in dt.Rows)
                {
                    sb.Append("{");
                    foreach (DataColumn dc in dr.Table.Columns)
                    {
                        sb.Append("\"");
                        sb.Append(dc.ColumnName);
                        sb.Append("\":\"");
                        if (dr[dc] != null && dr[dc] != DBNull.Value && dr[dc].ToString() != "")
                            sb.Append(dr[dc]).Replace("\\", "/");
                        else
                            sb.Append("");
                        sb.Append("\",");
                    }
                    sb = sb.Remove(sb.Length - 1, 1);
                    sb.Append("},");
                }
                sb = sb.Remove(sb.Length - 1, 1); 

            }
            else if (dt != null)
            {
                sb.Append("{");
                foreach (DataColumn dc in dt.Columns)
                {
                    sb.Append("\"");
                    sb.Append(dc.ColumnName);
                    sb.Append("\":\"");
                    sb.Append("");
                    sb.Append("\",");
                }
                sb = sb.Remove(sb.Length - 1, 1);
                sb.Append("}");
            }
            sb.Append("]");
            return JsonCharFilter(sb.ToString());
        }

        /// <summary>
        /// DataTable转Json
        /// </summary>
        /// <param name="dt">table数据集</param>
        /// <param name="dtName">json名</param>
        /// <returns></returns>
        public static string DataTableToJson(DataTable dt, string dtName,string splitLeft)
        {
            string splitRight = splitLeft == "{" ? "}" : "]";
            StringBuilder sb = new StringBuilder();
            sb.Append("" + splitLeft + "\"");
            sb.Append(dtName);
            sb.Append("\":[");
            if (DataTableHelper.IsExistRows(dt))
            {
                foreach (DataRow dr in dt.Rows)
                {
                    sb.Append("" + splitLeft + "");
                    foreach (DataColumn dc in dr.Table.Columns)
                    {
                        sb.Append("\"");
                        sb.Append(dc.ColumnName);
                        sb.Append("\":\"");
                        if (dr[dc] != null && dr[dc] != DBNull.Value && dr[dc].ToString() != "")
                            sb.Append(dr[dc]).Replace("\\", "/");
                        else
                            sb.Append("");
                        sb.Append("\",");
                    }
                    sb = sb.Remove(sb.Length - 1, 1);
                    sb.Append("" + splitRight + ",");
                }
                sb = sb.Remove(sb.Length - 1, 1);
            }
            sb.Append("]" + splitRight + "");
            return JsonCharFilter(sb.ToString());
        }

        /// <summary>
        /// 数据行转Json
        /// </summary>
        /// <param name="dr">数据行</param>
        /// <returns></returns>
        public static string DataRowToJson(DataRow dr)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("{");
            foreach (DataColumn dc in dr.Table.Columns)
            {
                sb.Append("\"");
                sb.Append(dc.ColumnName);
                sb.Append("\":\"");
                if (dr[dc] != null && dr[dc] != DBNull.Value && dr[dc].ToString() != "")
                    sb.Append(dr[dc]);
                else
                    sb.Append(" ");
                sb.Append("\",");
            }
            sb = sb.Remove(0, sb.Length - 1);
            sb.Append("},");
            return sb.ToString();
        }

        /// <summary>
        /// 将表转成jquery.dataTable格式
        /// </summary>
        /// <param name="dt">数据源</param>
        /// <param name="firstCheck">第一列是否为选中列</param>
        /// <returns></returns>
        public static string DataTableToJTable(DataTable dt,string key,string dataName,bool firstCheck)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("\""+dataName);
            sb.Append("\":[");
            if (DataTableHelper.IsExistRows(dt))
            {
                foreach (DataRow dr in dt.Rows)
                {
                    sb.Append("[");
                    //第一列是否为选中
                    if (firstCheck)
                        sb.Append("\"<input type=‘checkbox‘ class=‘checkboxes‘ value=‘"+dr[key].ToString()+"‘/>\",");
                    foreach (DataColumn dc in dr.Table.Columns)
                    {
                        sb.Append("\"");
                        if (dr[dc] != null && dr[dc] != DBNull.Value && dr[dc].ToString() != "")
                            sb.Append(dr[dc]).Replace("\\", "/");
                        else
                            sb.Append("");
                        sb.Append("\",");
                    }
                    sb = sb.Remove(sb.Length - 1, 1);
                    sb.Append("],");
                }
                sb = sb.Remove(sb.Length - 1, 1);
            }
            sb.Append("]");
            return JsonCharFilter(sb.ToString());
        }
        /// <summary>
        /// 数组转Json
        /// </summary>
        /// <param name="strs"></param>
        /// <returns></returns>
        public static string ArrayToJson(string[] strs)
        {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < strs.Length; i++)
            {
                sb.AppendFormat("‘{0}‘:‘{1}‘,", i + 1, strs[i]);
            }
            if (sb.Length > 0)
                return "{" + sb.ToString().TrimEnd(‘,‘) + "}";
            return "";
        }

        #region ListToJson
        /// <summary>
        /// list 转换json格式
        /// </summary>
        /// <param name="jsonName">类名</param>
        /// <param name="objlist">list集合</param>
        /// <returns></returns>
        public static string ListToJson<T>(List<T> objlist, string jsonName)
        {
            string result = "{";
            //如果没有给定类的名称, 指定一个
            if (jsonName.Equals(string.Empty))
            {
                object o = objlist[0];
                jsonName = o.GetType().ToString();
            }
            result += "\"" + jsonName + "\":[";
            //处理第一行前面不加","号
            bool firstline = true;
            foreach (object oo in objlist)
            {
                if (!firstline)
                {
                    result = result + "," + ObjectToJson(oo);
                }
                else
                {
                    result = result + ObjectToJson(oo) + "";
                    firstline = false;
                }
            }
            return result + "]}";
        }

        /// <summary>
        /// 单个对象转换json
        /// </summary>
        /// <param name="o">对象</param>
        /// <returns></returns>
        private static string ObjectToJson(object o)
        {
            string result = "{";
            List<string> ls_propertys = new List<string>();
            ls_propertys = GetObjectProperty(o);
            foreach (string str_property in ls_propertys)
            {
                if (result.Equals("{"))
                {
                    result = result + str_property;
                }
                else
                {
                    result = result + "," + str_property + "";
                }
            }
            return result + "}";
        }

        /// <summary>
        /// 获取对象属性
        /// </summary>
        /// <param name="o">对象</param>
        /// <returns></returns>
        private static List<string> GetObjectProperty(object o)
        {
            List<string> propertyslist = new List<string>();
            PropertyInfo[] propertys = o.GetType().GetProperties();
            foreach (PropertyInfo p in propertys)
            {
                propertyslist.Add("\"" + p.Name.ToString() + "\":\"" + p.GetValue(o, null) + "\"");

            }
            return propertyslist;
        }

        #endregion

        public static string HashtableToJson(Hashtable data, string dtName)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("{\"");
            sb.Append(dtName);
            sb.Append("\":[{");
            foreach (object key in data.Keys)
            {
                object value = data[key];
                sb.Append("\"");
                sb.Append(key);
                sb.Append("\":\"");
                if (!String.IsNullOrEmpty(value.ToString()) && value != DBNull.Value)
                {
                    sb.Append(value).Replace("\\", "/");
                }
                else
                {
                    sb.Append(" ");
                }
                sb.Append("\",");
            }
            sb = sb.Remove(sb.Length - 1, 1);
            sb.Append("}]}");
            return JsonCharFilter(sb.ToString());
        }
        /// <summary>
        /// Json特符字符过滤
        /// </summary>
        /// <param name="sourceStr">要过滤的源字符串</param>
        /// <returns>返回过滤的字符串</returns>
        private static string JsonCharFilter(string sourceStr)
        {
            return sourceStr;
        }

        /// <summary>
        /// 将JSon转成对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="data"></param>
        /// <returns></returns>
        public static object JsonToObejct<T>(string data)
        {
             JavaScriptSerializer json = new JavaScriptSerializer();
             return json.Deserialize<T>(data);
        }

        /// <summary>
        /// 获取对象属性
        /// </summary>
        /// <param name="o">对象</param>
        /// <returns></returns>
        public static Hashtable GetHashTableFromObjectProperty(object o)
        {
            Hashtable propertyslist = new Hashtable();
            PropertyInfo[] propertys = o.GetType().GetProperties();
            foreach (PropertyInfo p in propertys)
            {
                propertyslist.Add(p.Name.ToString(), p.GetValue(o, null));

            }
            return propertyslist;
        }

        /// <summary>
        /// Json 字符串 转换为 DataTable数据集合
        /// </summary>
        /// <param name="json"></param>
        /// <returns></returns>
        public static DataTable JsonToDataTable(string json)
        {
            if (json.StartsWith(","))
                json = json.Remove(0, 1);
            if (json.EndsWith(","))
                json = json.Remove(json.Length - 1);
            if (json.Contains("},") == false)
                json = json.Replace("}", "},");
            if (json.EndsWith(","))
                json = json.Remove(json.Length - 1);

            DataTable dataTable = new DataTable();  //实例化
            DataTable result;
            try
            {
                json = "[" + json + "]";
                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;
        }
        /// <summary>
        /// 将一个copy
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="post"></param>
        /// <param name="jsonData"></param>
        public static T JsonCopyObject<T>(T source, T target)
        {
            var tFields = target.GetType().GetProperties();
            var sFields = source.GetType().GetProperties();

            foreach (var item in tFields)
            {
                if (item.Name == "CreateUser" || item.Name == "CreateTime" || item.Name == "UpdateUser" || item.Name == "UpdateUser") continue;
                object svalue = source.GetType().GetProperty(item.Name).GetValue(source, null);
                object tvalue = item.GetValue(target, null);
                if (svalue != null && !svalue.Equals(tvalue))
                {
                    item.SetValue(target, svalue, null);
                }

            }
            return target;
        }

        /// <summary>
        /// 将EF对象转成字符串
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="source"></param>
        /// <returns></returns>
        public static  string EntityToJson<T>(List<T> source)
        {
            var jSetting = new JsonSerializerSettings();
            jSetting.NullValueHandling = NullValueHandling.Include;
            IsoDateTimeConverter dtConverter = new IsoDateTimeConverter { DateTimeFormat = "yyyy-MM-dd HH:mm:ss" };
            jSetting.Converters.Add(dtConverter);
            jSetting.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
            return JsonConvert.SerializeObject(source, Formatting.Indented, jSetting);
        }

        /// <summary>
        /// 将EF对象转成字符串
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="source"></param>
        /// <returns></returns>
        public static string EntityToJson<T>(T source)
        {
            var jSetting = new JsonSerializerSettings();
            jSetting.NullValueHandling = NullValueHandling.Include;
            IsoDateTimeConverter dtConverter = new IsoDateTimeConverter { DateTimeFormat = "yyyy-MM-dd HH:mm:ss" };
            jSetting.Converters.Add(dtConverter);
            jSetting.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
            return JsonConvert.SerializeObject(source, Formatting.Indented, jSetting);
        }

    }
}

  

时间: 2024-10-27 13:20:58

对json进行封装的相关文章

PHP 开发 APP 接口总结 - JSON 方式封装通信接口

1.通信数据的标准格式 ( JSON ),包括: code:状态码(200,400等) message:提示信息(例如:数据返回成功.邮箱格式错误等) data:返回数据 2.JSON 方式封装通信接口 response.php <?php /** * 按json方式输出通信数据 * @param integer $code 状态码 * @param string $message 提示信息 * @param array $data 数据 * return string */ class Res

小蚂蚁学习APP接口开发(1)—— json方式封装通信接口

前段时间,和公司的一个安卓程序员配合开发一款简单的APP,因为第一次写,时间也紧张,总感觉写的不是那么的完美,趁着这段时间好好总结一下经验. 对于APP的请求,服务器返回的数据类型一般是json和xml. xml和json的区别: 可读性方面--xml占优.因为它是有很多个节点组成的,节点的名称可以自定义. 生成数据方面--json占优.在PHP中要生成一条json数据,只需要一个内置函数就可以实现,而xml则需要拼接字符串或者实例化对象才能够实现,所以,json更为简便一些. 传输速度方面--

[知了堂学习笔记]_JSON数据操作第2讲(JSON的封装与解析)

上一讲为大家讲了什么是JSON,那么这一讲为大家带来了在WEB项目中JSON的用法,也就是JSON的封装与解析. 此图是数据库中的部分内容 一.JSON封装 所谓的JSON封装,指的是在Servlet中将从数据库得到的数据转化成JSON格式的字符串. 那么什么是JSON格式的字符串? JSON格式的字符串就是指字符串的内容要完全符合JSON数据的格式 这个就是在servlet中输出的已经封装好的JSON格式字符串,在控制台输出的效果. 如何封装 在我自己的WEB中,原本想用原生态的JSON去封装

(原)编写JAVA工具之json自动封装成pojo

代码在最后 我个人是不太喜欢http和json,可能是游戏做的多了的原因的,对通信协议和通信方式特敏感,因此即使是做应用我也会选择rpc而非http,但是有时候因为各种原因,还是不的不处理标准的http+json的东西. 这一次也确实需要处理一大串json,就是将一大堆的json转换成标准的java pojo.也许小json串我们可以直接用JSONObject去提值就行了,但是如果json是这样: 一个拥有近百个不一样的字段的pojo,如果我们需要单独的去取值估计会疯掉,这还不是主要的,更蛋疼的

App接口中json方式封装通信接口

1 封装json通信接口的类 2 <?php 3 class Response{ 4 /** 5 * 按json方式输出通信数据 6 * @param integer $code状态码 7 * @param string $message 提示信息 8 * @param array $data数据 9 * return string 10 **/ 11 public static function json($code,$message="",$data=array()){ 12

PHP. 03 .ajax传输XML、 ajax传输json、封装

XML简介 XML 指可扩展标记语言 EXtensible Markup Language .设计的时候是用来传递数据的,虽然格式跟HTML类似 xml示例 <?xml version="1.0" encoding="UTF-8"?> <singer> <name>Jay</name> <age>18</age> <skill>Sing</skill> </sing

JSON方式封装通信接口

1.response.php <?php class Response{ /** *按json方式输出通信数据 *@param integer $code 状态码 *@param string $message 提示信息 *@param array $data 数据 *return string */ public static function json($code,$message,$data=array()){ if(!is_numeric($code)){ return ''; } $r

json方式封装接口通信

编写response类: <?php class response{ /** * 按json方式输出通信数据 * @param integer $code 状态码 * @param string $message 提示信息 * @param array $data 提示信息 * return string */ public static function json($code,$message = '',$data = array()){ if(!is_numeric($code)){ ret

01 json方式封装通信接口

新建一个json_api.php<?php class Response{ /** *按json方式输出通信 *@param integet $code 状态码 *@param string $message 提示信息 *@param array $data 数据 * return string */ public static function json($code,$message,$data=array()){ if(is_null($code)){ return ''; } $resul