转换Json格式帮助类
using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using System.Data;
using System.Collections; namespace AIMSCommon
{
/// <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>
/// 数据行转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>
/// 数组转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;
}
}
}
转换Json格式帮助类的更多相关文章
- fastJson在java后台转换json格式数据探究(二)--处理数组/List/Map
作者:buster2014 推荐:长安散人 fastJson在java后台转换json格式数据探究(二)--处理数组/List/Map JSON字符串与Java对象的转换 1.将Java对象或Java ...
- java list转换json格式
/** * 处理返回值(转换json格式和补零) * * @param resultDto5List * @param dateList * @return */ private JSONObject ...
- fastJson java后台转换json格式数据
什么事JSON? JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式. 易于人阅读和编写.同时也易于机器解析和生成. 它基于JavaScript Progra ...
- 字符串转换json格式
前台json转字符串传递后台时 用到: data: JSON.stringify({ "zh": zhanghao, "mm": mima }), 当后台返回前 ...
- 通用对象转换Json格式
public static string ObjectToJson<T>(IList<T> IL, params string[] args) { var Json = new ...
- 如何 DataTable格式转换json格式
1.序列化啊 宝贝!! public string DataTableToJsonWithJsonNet(DataTable table) { string jsonString=string.Em ...
- C#工具类:Json操作帮助类(转载)
原文转载自C#工具类:Json操作帮助类_IT技术小趣屋. Json序列化和反序列化在程序开发中时常会遇到,在C#中可以使用很多种方法实现对数据的Json序列化和反序列化,封装一个Json操作工具类来 ...
- 【转载】C#工具类:Json操作帮助类
Json序列化和反序列化在程序开发中时常会遇到,在C#中可以使用很多种方法实现对数据的Json序列化和反序列化,封装一个Json操作工具类来简化相应的操作,该工具类中包含以下功能:对象转JSON.数据 ...
- java后台对json格式数据的解析
Json 和 Jsonlib 的使用 什么是 Json JSON(JvaScript Object Notation)(官网网站:http://www.json.org/)是 一种轻量级的数据交换格式 ...
随机推荐
- 九度OJ - 题目1481:Is It A Tree?
题目描述: A tree is a well-known data structure that is either empty (null, void, nothing) or is a set o ...
- 【BZOJ 2875】 [Noi2012]随机数生成器
Description 给你6个数,m, a, c, x0, n, g Xn+1 = ( aXn + c ) mod m,求Xn m, a, c, x0, n, g<=10^18 Input ...
- mybatis从dao传入多个参数到sqlmap时dao中要使用map或实例对象(如:user)作为参数传入, 否则报错找不到属性getter方法
23:37 2015-07-02 注意1. 使用mybaits的resultMap查询时, 如果想传入多个参数(比如where 1=1动态多条件查询时)sqlmap文件中对应的方法中, selectL ...
- sentos 上安装vnc图形界面
一.安装gnome图形化桌面 CentOS 6.3 64位 #yum groupinstall -y "X Window System" #yum groupinstall - ...
- Form表单学习网站
HTML表单 -- form标签 -- 与浏览者交互:http://www.dreamdu.com/xhtml/tag_form/
- [Firefly引擎][学习笔记三][已完结]所需模块封装
原地址:http://www.9miao.com/question-15-54671.html 学习笔记一传送门学习笔记二传送门 学习笔记三导读: 笔记三主要就是各个模块的封装了,这里贴 ...
- C++: std::string 与 Unicode 如何结合?
关键字:std::string Unicode 转自:http://www.vckbase.com/document/viewdoc/?id=1293 一旦知道 TCHAR 和_T 是如何工作的,那么 ...
- 不定长内存池之apr_pool
内存池可有效降低动态申请内存的次数,减少与内核态的交互,提升系统性能,减少内存碎片,增加内存空间使用率,避免内存泄漏的可能性,这么多的优点,没有理由不在系统中使用该技术. 内存池分类: 1. ...
- HeadFirst设计模式之迭代器模式
一. 1.迭代器模式是对遍历集合元素的抽象 2.The Iterator Pattern provides a way to access the elements of an aggregate o ...
- ArcGIS Runtime for Android开发教程V2.0(4)基础篇---MapView
原文地址: ArcGIS Runtime for Android开发教程V2.0(4)基础篇---MapView - ArcGIS_Mobile的专栏 - 博客频道 - CSDN.NET http:/ ...