Loading

Api中子类继承父类后,子类设置JsonIgnore失效的补救

public class Person
{
    public string Name{get;set;}    
    
    public int Age{get;set;}
}

public class Student : Person
{
    public string Grade {get;set;}

    [Newtonsoft.Json.JsonIgnore]
    public new int Age{get;set;}
}

序列化Student,Age还是一样的输出

写一个转换类


using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;

///
<summary> /// 继承父类后,设置忽略序列化修补设置 /// </summary> public class JsonIgnoreContractResolver : DefaultContractResolver { //protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization) //{ // JsonProperty property = base.CreateProperty(member, memberSerialization); // //var ignore = property.GetCustomAttributes(typeof(JsonIgnoreAttribute), inherit: false) // // .OfType<JsonIgnoreAttribute>().SingleOrDefault(); // if (member.IsDefined(typeof(JsonIgnoreAttribute))) // { // property.ShouldSerialize = instance => false; // } // return property; //} protected override List<MemberInfo> GetSerializableMembers(Type objectType) { //Return properties that do NOT have the JsonIgnoreSerializationAttribute return objectType.GetProperties() .Where(pi => !Attribute.IsDefined(pi, typeof(JsonIgnoreAttribute))) .ToList<MemberInfo>(); } }

使用

var settings = new JsonSerializerSettings();
settings.ContractResolver = new JsonIgnoreContractResolver();

指定转换设置,进行操作,就能忽略掉标记了 

[Newtonsoft.Json.JsonIgnore]

的属性

posted @ 2024-08-26 11:07  jevan  阅读(10)  评论(0编辑  收藏  举报