【问题标题】:NewtonSoft ignore nested properties at runtime [duplicate]NewtonSoft 在运行时忽略嵌套属性 [重复]
【发布时间】:2021-03-16 22:21:46
【问题描述】:

根据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; }
        }
    }

【问题讨论】:

  • 要为DriverInformation 类型运行解析器,在为Person 创建属性列表时,必须首先包含Info 属性。一旦Info 属性出现在列表中,就会调用解析器来解析DriverInformation 类型,您可以对其属性应用过滤。
  • 您是否考虑过传递包含或排除属性列表而不是传递单个字符?
  • @weichch 你有样品吗?不确定我是否在关注你!

标签: c# json serialization json.net


【解决方案1】:

答案可以在Conditionally ignore nested property when serializing object找到GetSerializableMembers需要被覆盖。

【讨论】:

  • 好发现,您的问题似乎与那个问题重复。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-21
  • 2017-09-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多