一个JSON序列化类,可序列化匿名类型

/// <summary>
    /// Json扩展方法类(编译时检查,类型安全)
    /// </summary>
    public static class JsonContextExtension
    {
        /// <summary>
        /// 从一个对象信息生成Json串
        /// </summary>
        /// <param name="obj">转换对象</param>
        /// <typeparam name="T">对象类型</typeparam>
        /// <returns></returns>
        public static string ToJson<T>(this T obj)
        {
            if (typeof(T).FullName.Contains("<>f__AnonymousType"))
            {
                //匿名类型
                var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
                return serializer.Serialize(obj);
            }
            else
            {
                var serializer = new DataContractJsonSerializer(typeof(T));
                string json = string.Empty;
                using (MemoryStream stream = new MemoryStream())
                {
                    serializer.WriteObject(stream, obj);
                    json = Encoding.UTF8.GetString(stream.ToArray());
                    stream.Close();
                }
                return json;
            }
        }
        /// <summary>
        /// 从一个Json串生成对象信息
        /// </summary>
        /// <param name="jsonString">JSON字符串</param>
        /// <typeparam name="T">对象类型</typeparam>
        /// <returns></returns>
        public static T JsonToObject<T>(this string jsonString)
        {

            DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
            using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(jsonString)))
            {
                var jsonobj = (T)serializer.ReadObject(stream);
                stream.Close();
                return jsonobj;
            }
        }
    }

 

posted @ 2011-12-09 17:46  白菜89  阅读(1225)  评论(1编辑  收藏  举报