C# JSON的序列化与反序列化

需要添加引用:System.ServiceModel.Web 和 System.Runtime.Serialization,然后使用Using:

using System.Runtime.Serialization.Json;

using System.Runtime.Serialization;

        /// <summary>
        /// 将对象转为Json
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string getJsonFromEntity<T>(T obj)
        {
            var jser = new JavaScriptSerializer();
            var json = jser.Serialize(obj);
            return json;
        }

        /// <summary>
        /// 解析JSON字符串生成对象实体
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="jsonString"></param>
        /// <returns></returns>
        public static T DeserializeJsonToObject<T>(string jsonString)
        {
            using (var ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString)))
            {
                return (T)new DataContractJsonSerializer(typeof(T)).ReadObject(ms);
            }
        }