首頁 > 軟體

C#中物件與JSON字串互相轉換的三種方式

2022-07-23 18:01:04

JSON(JavaScriptObject Notation, JS 物件標記) 是一種輕量級的資料交換格式。

關於記憶體物件和JSON字串的相互轉換,在實際專案中應比較廣泛,經過一番搜尋,找到如下三種方法來解決此問題

分別是使用Newtonsoft.Json.dllDataContractJsonSerializerJavaScriptSerializer

方法一: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();
        }

程式執行結果:

執行結果:

效能對比:

綜上所述,一般採用Json.NET方法一比較好!

參考:

JavaScriptSerializer類介紹:https://msdn.microsoft.com/zh-cn/library/system.web.script.serialization.javascriptserializer(v=vs.110).aspx

DataContractJsonSerializer類介紹:https://msdn.microsoft.com/zh-cn/library/system.runtime.serialization.json.datacontractjsonserializer(v=vs.110).aspx

以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,謝謝大家對it145.com的支援。如果你想了解更多相關內容請檢視下面相關連結


IT145.com E-mail:sddin#qq.com