Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Applying JsonMediaTypeFormatter to Json

Tags:

json

c#

json.net

I have the following formatter

 JsonMediaTypeFormatter formatter = new JsonMediaTypeFormatter();
 formatter.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;
 formatter.SerializerSettings.Formatting = Newtonsoft.Json.Formatting.Indented;
 formatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();

I would like to apply this formatting when serializing an object

 var jsonString = JsonConvert.SerializeObject(obj, formatter);

However, I am getting an error stating

 Cannot convert from System.Net.Http.Formatting.JsonMediaTypeFormatter to Newtonsoft.Json.Formatting
like image 708
blue piranha Avatar asked Aug 23 '17 15:08

blue piranha


1 Answers

Try following, it works fine in my case:

// Create a Serializer with specific tweaked settings, like assigning a specific ContractResolver

    var newtonSoftJsonSerializerSettings = new JsonSerializerSettings
    {
        ReferenceLoopHandling = ReferenceLoopHandling.Ignore, // Ignore the Self Reference looping
        PreserveReferencesHandling = PreserveReferencesHandling.None, // Do not Preserve the Reference Handling
        ContractResolver = new CamelCasePropertyNamesContractResolver(), // Make All properties Camel Case
        Formatting = Newtonsoft.Json.Formatting.Indented
    };

// To the final serialization call add the formatter as shown underneath

var result = JsonConvert.SerializeObject(obj,newtonSoftJsonSerializerSettings.Formatting);

Or

 var result = JsonConvert.SerializeObject(obj,Newtonsoft.Json.Formatting.Indented);

In actual code this is how we use the Json serializer with specific settings, for a MVC project, using the newtonSoftJsonSerializerSettings created above:

  // Fetch the HttpConfiguration object
  HttpConfiguration jsonHttpconfig = GlobalConfiguration.Configuration;    

// Add the Json Serializer to the HttpConfiguration object
    jsonHttpconfig.Formatters.JsonFormatter.SerializerSettings = newtonSoftJsonSerializerSettings;

    // This line ensures Json for all clients, without this line it generates Json only for clients which request, for browsers default is XML
    jsonHttpconfig.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));

Thus all the Http requests are serialized using the same serializer (newtonSoftJsonSerializerSettings)

like image 183
Mrinal Kamboj Avatar answered Nov 15 '22 09:11

Mrinal Kamboj