自已写的Json序列化方法,可以序列话对象的只读属性

时间:2023-03-09 15:34:01
自已写的Json序列化方法,可以序列话对象的只读属性
/*
* by zhangguozhan 2015/1/5
* P2B.Common.CJson.ConvertJson.ObjectToJson<SenderDomainModel>方法无法序列号只读属性。下面的实现填补了这个不足
*/
/// <summary>
/// 将对象转换成JSON字符串
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="obj"></param>
/// <returns></returns>
public static string ObjectToJson<T>(T obj) where T : class
{
if (obj == null)
return "object null"; string json = string.Empty;
var properties = obj.GetType().GetProperties();
if (properties == null || !properties.Any()) return json;
foreach (var property in properties)
{
if (!property.CanRead) continue;
if (property.MemberType != System.Reflection.MemberTypes.Property) continue;
string pName = property.Name;
var pValue = property.GetValue(obj, null);
if (/*property.PropertyType*/pValue is System.ValueType
|| pValue is string)
{
json += string.Format(",\"{0}\":\"{1}\"", pName, pValue == null ? "null" : pValue);
}
else
{
string subValue = string.Empty;
if (pValue is System.Collections.IList)
{
var list = (pValue as System.Collections.IList);
if (list.Count > )
{
string subJsons = string.Empty;
foreach (var item in list)
{
subJsons += "," + ObjectToJson(item);
}
if (!string.Empty.Equals(subJsons))
subValue = subJsons.Substring();
}
}
else
{
subValue = ObjectToJson(pValue);
} if (!string.Empty.Equals(subValue))
{
json += string.Format(",\"{0}\":[{1}]", pName, subValue);
}
}
}
if (json.Length > )
json = "{" + json.Substring() + "}";
return json;
}