JSON 序列化类 南京酷得软件

using System;
using System.Net;
using System.IO;
using System.Runtime.Serialization.Json;
using System.Text;

namespace SFiresoft.Util
{
    /// <summary>
    /// 提供对JSON格式数据的序列化及反序列化操作类
    /// </summary>
    /// <remarks>
    /// 南京酷得软件 sucsy 2011-8-2
    /// </remarks>
    public class JsonSerializer
    {
        #region JSON序列化操作函数
        /// <summary>
        /// 将传入的数据模型对象序列化为Json
        /// </summary>
        /// <param name="item">要序列化为JSON字符串的对象</param>
        /// <returns></returns>
        public static string JsonSerialize<T>(T item)
        {
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
            using (MemoryStream ms = new MemoryStream())
            {
                serializer.WriteObject(ms, item);
                StringBuilder sb = new StringBuilder();
                sb.Append(Encoding.UTF8.GetString(ms.ToArray(), 0, ms.ToArray().Length));
                return sb.ToString();
            }
        }
        #endregion

        #region JSON反序列化操作函数【包含对流数据及字符串数据两种数据类型的反序列化重载】
        /// <summary>
        /// 将传入的Json序列化为指定的数据模型
        /// </summary>
        /// <param name="mystream">传入的Json</param>
        /// <returns></returns>
        public static T JsonDeserialize<T>(Stream mystream) where T : class
        {
            MemoryStream memoryStream = new MemoryStream();
            int bytes = 1;
            byte[] temp = new byte[4096];
            while (bytes > 0)
            {
                bytes = mystream.Read(temp, 0, temp.Length);
                memoryStream.Write(temp, 0, bytes);
            }
            DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
            memoryStream.Position = 0;
            return (T)ser.ReadObject(memoryStream);
        }

        /// <summary>
        /// 将Json字符串转换为对象
        /// </summary>
        /// <param name="jsonString">JSON字符串</param>
        /// <returns></returns>
        public static T JsonDeserialize<T>(string jsonString) where T : class
        {
            MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
            DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
            return (T)ser.ReadObject(ms);
        }
        #endregion
    }
}

南京酷得软件

公司网站: http://www.codersoft.cn 专业开发: 气象软件、监狱网上购物系统、两法衔接平台
原文地址:https://www.cnblogs.com/sucsy/p/3099221.html