JSONFormat.cs 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Reflection;
  5. using System.Text;
  6. namespace Core.Mes.Client.Comm.Format
  7. {
  8. /// <summary>
  9. /// JSON格式转换类
  10. /// </summary>
  11. public class JSONFormat
  12. {
  13. /// <summary>
  14. /// 将实体对象转换成JSON格式字符串
  15. /// </summary>
  16. /// <param name="obj">需转换的实体对象</param>
  17. /// <returns>JSON格式字符串</returns>
  18. public static string Format(Object obj)
  19. {
  20. StringBuilder formatStr = new StringBuilder();
  21. Type type = obj.GetType();
  22. formatStr.Append("{");
  23. PropertyInfo[] properties = type.GetProperties();
  24. string name = "";
  25. Object value = null;
  26. for (int i = 0; i < properties.Length; i++)
  27. {
  28. value = properties[i].GetValue(obj, null);
  29. name = properties[i].Name;
  30. formatStr.Append("\"" + ((name != null && name.Length > 0) ? (name.Substring(0, 1).ToLower() + name.Substring(1)) : "") + "\":\"" + escape(value != null ? value.ToString() : "") + "\",");
  31. }
  32. formatStr.Remove(formatStr.Length - 1, 1);
  33. formatStr.Append("}");
  34. return formatStr.ToString();
  35. }
  36. /// <summary>
  37. /// json特殊字符转义
  38. /// </summary>
  39. /// <param name="json">old json</param>
  40. /// <returns>new json</returns>
  41. public static string escape(string json)
  42. {
  43. string newJson = "";
  44. if (!string.IsNullOrEmpty(json))
  45. {
  46. newJson = json.Replace("\\", "\\\\").Replace("\r", "\\r").Replace("\n", "\\n").Replace("\"", "\\\"");
  47. }
  48. return newJson;
  49. }
  50. }
  51. }