C#程序将对象转为json

一般情况下,使用

JsonConvert.SerializeObject(obj)

反序列

Object obji = JsonConvert.DeserializeObject<Object>(json数据);  // 尖括号<>中填入对象的类名 
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;
        }

自定义方法

原地址:C#将对象转化成json字符串 - 码农教程 (manongjc.com)

posted @ 2022-05-10 09:08  学竹  阅读(2877)  评论(0编辑  收藏  举报