C# 对象与JSON字符串互相转换的三种方式

JSON(JavaScript Object Notation, JS 对象标记) 是一种轻量级的数据交换格式。

  关于内存对象和JSON字符串的相互转换,在实际项目中应比较广泛,经过一番搜索,找到如下三种方法来解决此问题

分别是使用 Newtonsoft.Json.dll、DataContractJsonSerializer、 JavaScriptSerializer。 

建议使用:Json.NET方法!

方法一: Newtonsoft.Json.dll 

Newtonsoft.Json.dll在.net2.0之后的版本可以支持 版本.net framework4.0

添加Newtonsoft.json的引用

对象与json字符串转换类设计

class JsonNewtonsoft
    {
        /// <summary>
        /// 把对象转换为JSON字符串
        /// </summary>
        /// <param name="o">对象</param>
        /// <returns>JSON字符串</returns>
        public static string ToJSON(this object o)
        {
            if (o == null)
            {
                return null;
            }
            return JsonConvert.SerializeObject(o);
        }
        /// <summary>
        /// 把Json文本转为实体
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="input"></param>
        /// <returns></returns>
        public static T FromJSON<T>(this string input)
        {
            try
            {
                return JsonConvert.DeserializeObject<T>(input);
            }
            catch (Exception ex)
            {
                return default(T);
            }
        }
    }

方法二:DataContractJsonSerializer

 使用这种 需要引用 System.Runtime.Serialization.dll

class JsonDataContractJsonSerializer
    {
        /// <summary>
        /// 内存对象转换为json字符串
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string ObjectToJson(object obj)
        {
           DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
           MemoryStream stream = new MemoryStream();
           serializer.WriteObject(stream, obj);
           byte[] dataBytes = new byte[stream.Length];
           stream.Position = 0;
           stream.Read(dataBytes, 0, (int)stream.Length);
           return Encoding.UTF8.GetString(dataBytes);
        }
       /// <summary>
       /// Json字符串转内存对象
       /// </summary>
       /// <param name="jsonString"></param>
       /// <param name="obj"></param>
       /// <returns></returns>
        public static object JsonToObject(string jsonString, object obj)
        {
           DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
           MemoryStream mStream = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
           return serializer.ReadObject(mStream);
        }
    }

方法三:JavaScriptSerializer

需要引用:System.Web.Extensions.dll

类设计

public static class JsonJavaScriptSerializer
    {
        /// <summary>
        /// 内存对象转换为json字符串
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string ToJSON(object obj)
        {
            StringBuilder sb = new StringBuilder();
            JavaScriptSerializer json = new JavaScriptSerializer();
            json.Serialize(obj, sb);
            return sb.ToString();
        }
        /// <summary>
        /// Json字符串转内存对象
        /// </summary>
        /// <param name="jsonString"></param>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static T FromJSON<T>(string jsonString)
        {
            JavaScriptSerializer json = new JavaScriptSerializer();
            return json.Deserialize<T>(jsonString);
        }

    }

程序测试:

新建一个测试对象类Student.cs

public enum Sex
    {
        男=0,
        女=1
    }
    [Serializable()]
    class Student
    {
        private string _name;

        public string Name
        {
            get { return _name; }
            set { _name = value; }
        }

        private int _age;

        public int Age
        {
            get { return _age; }
            set { _age = value; }
        }

        private Sex _sex = Sex.男;

        public Sex Sex
        {
            get { return _sex; }
            set { _sex = value; }
        }
        public Student()
        { }
        public Student(string name,int age,Sex sex)
        {
            this._name = name;
            this._age = age;
            this._sex = sex;
        }
    }

测试程序

static void Main(string[] args)
        {
            Student st = new Student("笨男孩",22,Sex.男);

            Console.WriteLine("============方法一============================================");
            //方法一

            Console.WriteLine("方法一对象转Json字符串");
            string jsonStr = JsonNewtonsoft.ToJSON(st);
            Console.WriteLine(jsonStr);
            Console.WriteLine("方法一Json字符串转对象");
            Student stobj = (Student)JsonNewtonsoft.FromJSON<Student>(jsonStr);
            Console.WriteLine("姓名:{0} 年龄:{1} 性别:{2}",stobj.Name,stobj.Age,stobj.Sex);


            Console.WriteLine("============方法二============================================");
            //方法二
            Console.WriteLine("方法二对象转Json字符串");
            string jsonStr2 = JsonDataContractJsonSerializer.ToJSON(st);
            Console.WriteLine(jsonStr2);
            Console.WriteLine("方法二Json字符串转对象");
            Student stobj2 = (Student)JsonDataContractJsonSerializer.FromJSON(jsonStr2, st);
            Console.WriteLine("姓名:{0} 年龄:{1} 性别:{2}", stobj2.Name, stobj2.Age, stobj2.Sex);


            Console.WriteLine("============方法三============================================");
            //方法二
            Console.WriteLine("方法三对象转Json字符串");
            string jsonStr3 = JsonJavaScriptSerializer.ToJSON(st);
            Console.WriteLine(jsonStr3);
            Console.WriteLine("方法三Json字符串转对象");
            Student stobj3 = (Student)JsonJavaScriptSerializer.FromJSON<Student>(jsonStr3);
            Console.WriteLine("姓名:{0} 年龄:{1} 性别:{2}", stobj3.Name, stobj3.Age, stobj3.Sex);

            Console.ReadKey();
        }
性能对比:功能对比:请参考链接,感谢作者分享:C# 对象与JSON字符串互相转换的三种方式 - 奋斗的中年人哈哈哈 - 博客园 (cnblogs.com)

posted on 2022-11-19 11:33  Violin_Huang  阅读(372)  评论(0编辑  收藏  举报

导航