zoukankan      html  css  js  c++  java
  • C#将对象转化成json字符串

    一般情况下,使用

    JsonConvert.SerializeObject(obj)

    即可

    也可以使用下面的方法

            public string ToJson<T>(T obj) where T : class
            {
                string res = "";
                Type t = typeof(T);
                foreach(var item in t.GetProperties())
                {
                    if (obj != null)
                    {
                        if (item.PropertyType.IsPrimitive || item.PropertyType == typeof(string))    //基础数据类型,非自定义的class或者struct
                        {
                            res += """ + item.Name + "":"" + item.GetValue(obj) + "",";
                        }
                    }
                    else
                    {
                        if (item.PropertyType.IsPrimitive || item.PropertyType == typeof(string))   //对象为空直接赋双引号
                        {
                            res += """ + item.Name + "":"",";
                        }
                    }                              
                }
                Char[] mychar = { ',' };
                res = res.TrimEnd(mychar);       //去除末尾的逗号
                return res;
            }

    使用这个方法,如果对象里面有自定义的类,可以自动排除。

    记录编程的点滴,体会学习的乐趣
  • 相关阅读:
    poj2739
    poj1469
    poj2010
    poj1179
    poj1778
    使用数组实现ArrayList的效果
    zgb老师关于java集合的总结
    jah老师中关于集合的总结
    继承一个类或者是实现一个接口注意点
    5、Iterator迭代器的使用
  • 原文地址:https://www.cnblogs.com/AduBlog/p/15040355.html
Copyright © 2011-2022 走看看