需要在序列化时候,忽略掉某些字段,对Newtonsoft.Json进行全局配置,如下:
1. 自定 ContractResolver
public class MyContractResolver : DefaultContractResolver { protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization) { if (!typeof(EntityBase).IsAssignableFrom(type)) { return base.CreateProperties(type, memberSerialization); } IList<JsonProperty> props = base.CreateProperties(type, memberSerialization); foreach (var prop in props) { if (prop.DeclaringType.FullName != null && prop.DeclaringType.FullName.StartsWith("PWMIS.DataMap.Entity.EntityBase")) { prop.Ignored = true; } } return props; } }
2. 应用程序启动的时候对JsonConvert进行默认配置:
JsonSerializerSettings setting = new JsonSerializerSettings() { Formatting = Formatting.None, ContractResolver = new MyContractResolver() }; JsonConvert.DefaultSettings = new Func<JsonSerializerSettings>(() => { //日期类型默认格式化处理 setting.DateFormatHandling = Newtonsoft.Json.DateFormatHandling.MicrosoftDateFormat; setting.DateFormatString = "yyyy-MM-dd HH:mm:ss"; //空值处理 setting.NullValueHandling = NullValueHandling.Ignore; return setting; });