buguge - Keep it simple,stupid

知识就是力量,但更重要的,是运用知识的能力why buguge?

导航

自已写的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 > 0)
                {
                    string subJsons = string.Empty;
                    foreach (var item in list)
                    {
                        subJsons += "," + ObjectToJson(item);
                    }
                    if (!string.Empty.Equals(subJsons))
                        subValue = subJsons.Substring(1);
                }
            }
            else
            {
                subValue = ObjectToJson(pValue);
            }

            if (!string.Empty.Equals(subValue))
            {
                json += string.Format(",\"{0}\":[{1}]", pName, subValue);
            }
        }
    }
    if (json.Length > 0)
        json = "{" + json.Substring(1) + "}";
    return json;
}

 

posted on 2015-01-05 15:02  buguge  阅读(642)  评论(0编辑  收藏  举报