C# 编写通用的JSON数据进行序列化和反序列化

时间:2023-12-04 22:22:56

注意事项:使用JSON系列化和反系列化,必须要添加引用System.Runtime.Serialization。

1.通用类代码如下:

/// <summary>
    /// JSON序列化和反序列化辅助类
    /// </summary>
    public class JsonHelper
    {
        /// <summary>
        /// JSON序列化
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="t"></param>
        /// <returns></returns>
        public static string JsonSerializer<T>(T t)
        {
            DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
            MemoryStream ms = new MemoryStream();
            ser.WriteObject(ms, t);
            string jsonString = Encoding.UTF8.GetString(ms.ToArray());
            ms.Close();
            return jsonString;
        }

/// <summary>
        /// JSON反序列化
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="jsonString"></param>
        /// <returns></returns>
        public static T JsonDeserialize<T>(string jsonString)
        {
            DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
            MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
            T obj = (T)ser.ReadObject(ms);
            ms.Close();
            return obj;
        }
    }

2.定义调用类,如下:

/// <summary>
    /// 定义类
    /// </summary>
    public class Person
    {
        public string Name { get; set; }
        public int Age { get; set; }
    }

3.调用系列化和反系列化的操作如下:

Person p = new Person();
            p.Name = "陈磊";
            p.Age = 29;

//调用JSON系列化

string strJson = JsonHelper.JsonSerializer<Person>(p);
            Console.WriteLine(strJson);

//调用JSON反系列化
            string strDJson = "{\"Age\":28,\"Name\":\"陈磊\"}";
            Person dp = JsonHelper.JsonDeserialize<Person>(strDJson);
            Console.WriteLine(dp.Name + "," + dp.Age);