Json序列化和反序列化

引用程序集:System.Runtime.Serialization;

引用命令空间:System.Runtime.Serialization.Json;

public class JsonHelper

{

    /// <summary>

    /// 生成Json格式

    /// </summary>

    /// <typeparam name="T"></typeparam>

    /// <param name="obj"></param>

    /// <returns></returns>

    public static string JsonSerializer<T>(T obj)

    {

        //JavaScriptSerializer serialize = new JavaScriptSerializer();

        //return serialize.Serialize(obj);

        var json = new DataContractJsonSerializer(obj.GetType());

        using (var stream = new MemoryStream())

        {

            json.WriteObject(stream, obj);

            string szJson = Encoding.UTF8.GetString(stream.ToArray());

            return szJson;

        }

    }



    /// <summary>

    /// 获取Json的Model

    /// </summary>

    /// <typeparam name="T"></typeparam>

    /// <param name="szJson"></param>

    /// <returns></returns>

    public static T JsonDeserialize<T>(string szJson)

    {

        T obj = Activator.CreateInstance<T>();

        using (var ms = new MemoryStream(Encoding.UTF8.GetBytes(szJson)))

        {

            var serializer = new DataContractJsonSerializer(obj.GetType());

            return (T)serializer.ReadObject(ms);

        }

    }

}

 方式二:使用扩展方法

public static class JsonHelper

{

    /// <summary>

    /// 生成Json格式

    /// </summary>

    /// <typeparam name="T"></typeparam>

    /// <param name="obj"></param>

    /// <returns></returns>

    public static string JsonSerializer<T>(this T obj)

    {

        //JavaScriptSerializer serialize = new JavaScriptSerializer();

        //return serialize.Serialize(obj);

        var json = new DataContractJsonSerializer(obj.GetType());

        using (var stream = new MemoryStream())

        {

            json.WriteObject(stream, obj);

            string szJson = Encoding.UTF8.GetString(stream.ToArray());

            return szJson;

        }

    }



    /// <summary>

    /// 获取Json的Model

    /// </summary>

    /// <typeparam name="T"></typeparam>

    /// <param name="szJson"></param>

    /// <returns></returns>

    public static T JsonDeserialize<T>(this string szJson)

    {

        T obj = Activator.CreateInstance<T>();

        using (var ms = new MemoryStream(Encoding.UTF8.GetBytes(szJson)))

        {

            var serializer = new DataContractJsonSerializer(obj.GetType());

            return (T)serializer.ReadObject(ms);

        }

    }

}

你可能感兴趣的:(json)