代码之家  ›  专栏  ›  技术社区  ›  Saber

NewtonSoft在运行时为嵌套属性添加JSONIGNORE

  •  0
  • Saber  · 技术社区  · 5 年前

    根据 newtonSoft 文档,可以通过覆盖来动态忽略选定的属性 CreateProperties .

    是否可以动态忽略嵌套属性?

    举个例子

    public class DynamicContractResolver : DefaultContractResolver
    {
        private readonly char _startingWithChar;
    
        public DynamicContractResolver(char startingWithChar)
        {
            _startingWithChar = startingWithChar;
        }
    
        protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
        {
            IList<JsonProperty> properties = base.CreateProperties(type, memberSerialization);
    
            // only serializer properties that start with the specified character
            properties =
                properties.Where(p => p.PropertyName.StartsWith(_startingWithChar.ToString())).ToList();
    
            return properties;
        }
    }
    
    public class Person
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
    
        public string FullName
        {
            get { return FirstName + " " + LastName; }
        }
    }
    

    然后

    Person person = new Person
    {
        FirstName = "Dennis",
        LastName = "Deepwater-Diver"
    };
    
    string startingWithF = JsonConvert.SerializeObject(person, Formatting.Indented,
        new JsonSerializerSettings { ContractResolver = new DynamicContractResolver('F') });
    
    Console.WriteLine(startingWithF);
    // {
    //   "FirstName": "Dennis",
    //   "FullName": "Dennis Deepwater-Diver"
    // }
    

    但是如果 Person 看起来像这样,我们想忽略它 DriverID ?

      public class DriverInformation
      {
        public string DriverID {get;set;}
        public string Branch {get;set}
      }
    
      public class Person
        {
            public string FirstName { get; set; }
            public string LastName { get; set; }
            public DriverInformation Info {get;set}
        
            public string FullName
            {
                get { return FirstName + " " + LastName; }
            }
        }
    
    0 回复  |  直到 5 年前
        1
  •  1
  •   Saber    5 年前

    答案可以在 Conditionally ignore nested property when serializing object GetSerializableMembers 需要被超越。