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
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With