Applying JsonMediaTypeFormatter to Json

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 get an error

 Cannot convert from System.Net.Http.Formatting.JsonMediaTypeFormatter to Newtonsoft.Json.Formatting
+4
source share
1 answer

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 real code, we use Json serializerwith certain settings for the MVC project, using the one created above newtonSoftJsonSerializerSettings:

  // 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, everything is Http requestsserialized using the same serializer (newtonSoftJsonSerializerSettings)

+2
source

Source: https://habr.com/ru/post/1684310/


All Articles