码迷,mamicode.com
首页 > Windows程序 > 详细

C# 扩展方法—— 序列化与反序列化

时间:2019-12-23 15:18:37      阅读:105      评论:0      收藏:0      [点我收藏+]

标签:inf   日期   custom   strong   contract   comm   soft   tar   sub   

其他扩展方法详见:https://www.cnblogs.com/zhuanjiao/p/12060937.html

主要是是对日期格式的处理

using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;
using System;
using System.Collections.Generic;
using System.Reflection;
 
namespace CoSubject.Common.JsonNet
{
    public static class NewtonsoftJsonSerializer
    {
        public static JsonSerializerSettings Settings { get; private set; }
 
        static NewtonsoftJsonSerializer()
        {
            Settings = new JsonSerializerSettings
            {
                Converters = new List<JsonConverter> { new IsoDateTimeConverter() },
                ContractResolver = new CustomContractResolver(),
                ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor
            };
        }
 
        /// <summary>
        /// Serialize an object to json string.
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string Serialize(this object obj)
        {
            return obj == null ? null : JsonConvert.SerializeObject(obj, Settings);
        }
 
        /// <summary>
        /// Serialize an object to json string.
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="joinChar"></param>
        /// <returns></returns>
        public static string SerializeObjectTime(this object obj, string joinChar = "/")
        {
            Settings = new JsonSerializerSettings
            {
                Converters =
                    new List<JsonConverter>
                    {
                        new IsoDateTimeConverter()
                        {
                            DateTimeFormat =
                                string.Format( "yyyy{0}MM{0}dd HH:mm:ss",joinChar)
                        }
                    },
                ContractResolver = new CustomContractResolver(),
                ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor
            };
            return obj == null ? null : JsonConvert.SerializeObject(obj, Settings);
        }
 
        public static string SerializeObjectTimeNoSecond(this object obj, string joinChar = "/")
        {
            Settings = new JsonSerializerSettings
            {
                Converters =
                    new List<JsonConverter>
                    {
                        new IsoDateTimeConverter()
                        {
                            DateTimeFormat = string.Format( "yyyy{0}MM{0}dd HH:mm", joinChar)
                        }
                    },
                ContractResolver = new CustomContractResolver(),
                ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor
            };
            return obj == null ? null : JsonConvert.SerializeObject(obj, Settings);
        }
 
        public static string SerializeObjectDate(this object obj, string joinChar = "/")
        {
            Settings = new JsonSerializerSettings
            {
                Converters =
                    new List<JsonConverter>
                    {
                        new IsoDateTimeConverter()
                        {
                            DateTimeFormat = string.Format( "yyyy{0}MM{0}dd", joinChar)
                        }
                    },
                ContractResolver = new CustomContractResolver(),
                ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor
            };
            return obj == null ? null : JsonConvert.SerializeObject(obj, Settings);
        }
 
        /// <summary>
        /// Deserialize a json string to an object.
        /// </summary>
        /// <param name="value"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        public static object Deserialize(this string value, Type type)
        {
            return JsonConvert.DeserializeObject(value, type, Settings);
        }
 
        /// <summary>
        /// Deserialize a json string to a strong type object.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="value"></param>
        /// <param name="joinChar"></param>
        /// <returns></returns>
        public static T Deserialize<T>(this string value, string joinChar = "/") where T : class
        {
            Settings = new JsonSerializerSettings
            {
                Converters = new List<JsonConverter> { new IsoDateTimeConverter() { DateTimeFormat = string.Format("yyyy{0}MM{0}dd", joinChar) } },
                DateTimeZoneHandling = DateTimeZoneHandling.Utc
            };
            return JsonConvert.DeserializeObject<T>(value, Settings);
        }
 
        /// <summary>
        /// Deserialize a json string to a strong type object.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="value"></param>
        /// <param name="joinChar"></param>
        /// <returns></returns>
        public static T DeserializeNoSecond<T>(this string value, string joinChar = "/") where T : class
        {
            Settings = new JsonSerializerSettings
            {
                Converters = new List<JsonConverter> { new IsoDateTimeConverter() { DateTimeFormat = string.Format("yyyy{0}MM{0}dd HH:mm", joinChar) } },
                DateTimeZoneHandling = DateTimeZoneHandling.Utc
            };
            return JsonConvert.DeserializeObject<T>(value, Settings);
        }
 
        class CustomContractResolver : DefaultContractResolver
        {
            protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
            {
                var jsonProperty = base.CreateProperty(member, memberSerialization);
                if (jsonProperty.Writable) return jsonProperty;
                var property = member as PropertyInfo;
                if (property == null) return jsonProperty;
                var hasPrivateSetter = property.GetSetMethod(true) != null;
                jsonProperty.Writable = hasPrivateSetter;
                return jsonProperty;
            }
        }
    }
}

  

C# 扩展方法—— 序列化与反序列化

标签:inf   日期   custom   strong   contract   comm   soft   tar   sub   

原文地址:https://www.cnblogs.com/zhuanjiao/p/12083377.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!