`

C#中JSON序列化和反序列化

    博客分类:
  • C#
阅读更多

在做项目中使用EF时,发现DataContractJsonSerializer对EF中的实体,无论是接口or实现类进行序列化时,都会报:

{"The type 'XXXXXXXXXX' cannot be serialized to JSON because its IsReference setting is 'True'. The JSON format does not support references because there is no standardized format for representing references. To enable serialization, disable the IsReference setting on the type or an appropriate parent class of the type."}

网上看了一下解决方案:http://www.cnblogs.com/zhaojin/archive/2011/02/12/1952804.html 上说了一下,所以对

DataContractJsonSerializer和JavaScriptSerializer 都简单写一个(代码最直接,上代码)

一、DataContractJsonSerializer

引用System.Runtime.Serialization.dll

/// <summary>
        /// 序列化对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="t"></param>
        /// <returns></returns>
        public static string Serializer<T>(this T t)
        {
            string serialization = string.Empty;
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));

            using (var memoryStream = new MemoryStream())
            {
                serializer.WriteObject(memoryStream, t);

                serialization = Encoding.UTF8.GetString(memoryStream.ToArray());
            }

            return serialization;
        }

        /// <summary>
        /// 反序列化json到对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="json"></param>
        /// <returns></returns>
        public static T Deserializer<T>(this string json) where T : class
        {
            if (!string.IsNullOrEmpty(json))
            {
                T obj = null;
                DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));

                using (var memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(json)))
                {
                    obj = serializer.ReadObject(memoryStream) as T;
                }

                return obj;
            }
            return null;
        }

 

二、JavaScriptSerializer

引用System.Web.Extensions.dll

 

   /// <summary>
        /// 解决EF实体的序列化问题
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="t"></param>
        /// <returns></returns>
        public static string ScriptSerialize<T>(this T t)
        {

            JavaScriptSerializer js = new JavaScriptSerializer();

            return js.Serialize(t);

        }



        public static T ScriptDeserialize<T>(this string strJson)
        {

            JavaScriptSerializer js = new JavaScriptSerializer();

            return js.Deserialize<T>(strJson);

        }

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics