DotNet的JSON序列化與反序列化


   JSON(JavaScript Object Notation)JavaScript對象表示法,它是一種基於文本,獨立於語言的輕量級數據交換格式。在現在的通信中,較多的采用JSON數據格式,JSON有兩種表示結構,對象和數組,JSON 數據的書寫格式是:名稱/值對。

   在vs解決方案中以前采用xml樹的形式,組織項目的結構。在新的.net core中,項目的解決方案采用json作為項目的結構說明。

   在.net的前后台數據交互中,采用序列化對象為json,前端ajax接受傳輸數據,反序列化為對象,在頁面對數據進行渲染。有關json的相關內容就不再贅述,在.net中序列化的類主要采用DataContractJsonSerializer類。

   現在提供一個較為通用的json的序列化和反序列化的通用方法。

  1.json的序列化:

        /// <summary>
        /// 將對象序列化為JSON
        /// </summary>
        /// <typeparam name="T">序列化的類型</typeparam>
        /// <param name="t">需要序列化的對象</param>
        /// <returns>序列化后的JSON</returns>
        public static string JsonSerializer<T>(T t)
        {
            if (t == null)
                throw new ArgumentNullException("t");
            string jsonString;
            try
            {
                var ser = new DataContractJsonSerializer(typeof(T));
                var ms = new MemoryStream();
                ser.WriteObject(ms, t);
                jsonString = Encoding.UTF8.GetString(ms.ToArray());
                ms.Close();
                //替換Json的Date字符串
                const string p = @"\\/Date\((\d+)\+\d+\)\\/";
                var matchEvaluator = new MatchEvaluator(ConvertJsonDateToDateString);
                var reg = new System.Text.RegularExpressions.Regex(p);
                jsonString = reg.Replace(jsonString, matchEvaluator);
            }
            catch (Exception er)
            {
                throw new Exception(er.Message);
            }

            return jsonString;
        }

  2.json的反序列化:

       /// <summary>
        /// 將JSON反序列化為對象
        /// </summary>
        public static T JsonDeserialize<T>(string jsonString)
        {
            if (string.IsNullOrEmpty(jsonString))
                throw new Exception(jsonString);
            //將"yyyy-MM-dd HH:mm:ss"格式的字符串轉為"\/Date(1294499956278+0800)\/"格式
            const string p = @"\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}:\d{2}";
            try
            {
                var matchEvaluator = new MatchEvaluator(ConvertDateStringToJsonDate);
                var reg = new System.Text.RegularExpressions.Regex(p);
                jsonString = reg.Replace(jsonString, matchEvaluator);
                var ser = new DataContractJsonSerializer(typeof(T));
                var ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
                var obj = (T)ser.ReadObject(ms);
                return obj;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message, ex);
            }

        }

   以上是一個較為簡單的json序列化和反序列化方法。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM