Ignoring Properties in Newtonsoft.Json
Asp.Net Core MVC uses Newtonsoft.Json as it's json serializer (this might change in the future). Applying the
JsonIgnore attribute to a property of a class prevents it from being serialized.
The above approach works well if properties to be ignored are known ahead of time. A more flexible method - one where the properties are selected at runtime - would involve changing the behaviour of the method that creates the json version of the properties. In Newtonsoft.Json, this can be achieved by creating a subclass of
DefaultContractResolver and overriding its
IncludePropertyForSerialization method creates a collection of properties (for a given type) that should be considered for serialization based on what the caller provided in the request. When it's time to consider a property for serialization - which happens in the
CreateProperty method - it's
Ignored values are set accordingly.
A property will only get serialized if one of the following conditions is met:
serializedPropertiescollection does not contain any value for the specified type
serializedPropertiescollection contains an empty list of properties to be serialized
serializedPropertiescollection contains the targeted property for the specified type
Providing Caller's Input to DynamicFieldResolver
The final piece in the jigsaw is to create an ActionFilterAttribute to decorate a controller or any of its action methods. This filter will inspect the request's querystring and provide the list of fields to serialize to the field resolver and setup the
Applying the Filter Attribute
The snippet below shows an example of how to use this filter attribute.
The following sections highlights a few examples of the output.
The source code is available here.