using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
namespace Core.Mes.Client.Comm.Format
{
///
/// JSON格式转换类
///
public class JSONFormat
{
///
/// 将实体对象转换成JSON格式字符串
///
/// 需转换的实体对象
/// JSON格式字符串
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();
}
///
/// json特殊字符转义
///
/// old json
/// new json
public static string escape(string json)
{
string newJson = "";
if (!string.IsNullOrEmpty(json))
{
newJson = json.Replace("\\", "\\\\").Replace("\r", "\\r").Replace("\n", "\\n").Replace("\"", "\\\"");
}
return newJson;
}
}
}