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;
        }

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

记录编程的点滴,体会学习的乐趣
原文地址:https://www.cnblogs.com/AduBlog/p/15040355.html