0

According to newtonSoft documents, it's possible to dynamically ignore selected properties by overriding CreateProperties.

Is it possible to ignore nested properties dynamically?

As an example

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

And then

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"
// }

But what if Person looks like this, and we want do ignore 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; }
        }
    }
Saber
  • 5,150
  • 4
  • 31
  • 43
  • To run your resolver for `DriverInformation` type, you must first include `Info` property when creating property list for `Person`. Once the `Info` property is in the list, the resolver is invoked to resolve `DriverInformation` type, and you could apply filtering over its properties. – weichch Mar 17 '21 at 02:30
  • Instead of passing a single character have you considered to pass inclusion or exclusion list of properties? – Peter Csala Mar 17 '21 at 08:48
  • @weichch do you have a sample? not sure if I'm following you! – Saber Mar 17 '21 at 14:08

1 Answers1

1

The answer can be found in Conditionally ignore nested property when serializing object GetSerializableMembers needs to be overriden.

Saber
  • 5,150
  • 4
  • 31
  • 43