Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom Json.NET serializer settings per type

I am using an ApiController which uses the global HttpConfiguration class to specify the JsonFormatter settings. I can globally set serialization settings as follows very easily:

config.Formatters.JsonFormatter.SerializerSettings.PreserveReferencesHandling = PreserveReferencesHandling.Objects;

The problem is that not all settings apply to all types in my project. I want to specify custom TypeNameHandling and Binder options for specific types that perform polymorphic serialization.

How can I specify JsonFormatter.SerializationSettings on a per-type or at the least on a per-ApiController basis?

like image 650
Trevor Elliott Avatar asked Jul 16 '13 19:07

Trevor Elliott


People also ask

What is Jsonserializeroptions?

WriteIndented Property (System. Text. Json) Gets or sets a value that indicates whether JSON should use pretty printing.

What is JsonSerializerSettings?

Specifies the settings on a JsonSerializer object. Newtonsoft.Json.

What is JsonProperty annotation C#?

JsonPropertyAttribute indicates that a property should be serialized when member serialization is set to opt-in. It includes non-public properties in serialization and deserialization. It can be used to customize type name, reference, null, and default value handling for the property value.


1 Answers

Based on your comment above, following is an example of per-controller configuration:

[MyControllerConfig]
public class ValuesController : ApiController

[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = true)]
public class MyControllerConfigAttribute : Attribute, IControllerConfiguration
{
    public void Initialize(HttpControllerSettings controllerSettings, HttpControllerDescriptor controllerDescriptor)
    {
        //remove the existing Json formatter as this is the global formatter and changing any setting on it
        //would effect other controllers too.
        controllerSettings.Formatters.Remove(controllerSettings.Formatters.JsonFormatter);

        JsonMediaTypeFormatter formatter = new JsonMediaTypeFormatter();
        formatter.SerializerSettings.PreserveReferencesHandling = PreserveReferencesHandling.All;
        controllerSettings.Formatters.Insert(0, formatter);
    }
}
like image 142
Kiran Avatar answered Sep 28 '22 13:09

Kiran