| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455 |
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Reflection;
- using System.Text;
- namespace Core.Mes.Client.Comm.Format
- {
- /// <summary>
- /// JSON格式转换类
- /// </summary>
- public class JSONFormat
- {
- /// <summary>
- /// 将实体对象转换成JSON格式字符串
- /// </summary>
- /// <param name="obj">需转换的实体对象</param>
- /// <returns>JSON格式字符串</returns>
- public static string Format(Object obj)
- {
- StringBuilder formatStr = new StringBuilder();
- Type type = obj.GetType();
- formatStr.Append("{");
- PropertyInfo[] properties = type.GetProperties();
- string name = "";
- Object value = null;
- for (int i = 0; i < properties.Length; i++)
- {
- value = properties[i].GetValue(obj, null);
- name = properties[i].Name;
- formatStr.Append("\"" + ((name != null && name.Length > 0) ? (name.Substring(0, 1).ToLower() + name.Substring(1)) : "") + "\":\"" + escape(value != null ? value.ToString() : "") + "\",");
- }
- formatStr.Remove(formatStr.Length - 1, 1);
- formatStr.Append("}");
- return formatStr.ToString();
- }
- /// <summary>
- /// json特殊字符转义
- /// </summary>
- /// <param name="json">old json</param>
- /// <returns>new json</returns>
- public static string escape(string json)
- {
- string newJson = "";
- if (!string.IsNullOrEmpty(json))
- {
- newJson = json.Replace("\\", "\\\\").Replace("\r", "\\r").Replace("\n", "\\n").Replace("\"", "\\\"");
- }
- return newJson;
- }
- }
- }
|