zoukankan      html  css  js  c++  java
  • 自已写的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;
    }
  • 相关阅读:
    linux kernel ftrace 之wakeup tracer and wakeup_rt tracer
    urb传输的代码分析
    open/ioctl in kernel
    淺談C51記憶體優化(data idata xdata)
    8051 XDATA
    Android.bp
    android bionic
    echo +80 > /sys/class/rtc/rtc0/wakealarm
    高清地图下载
    更新和删除数据
  • 原文地址:https://www.cnblogs.com/buguge/p/4203611.html
Copyright © 2011-2022 走看看