Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set default global json serializer settings

I'm trying to set the global serializer settings like this in my global.asax.

var formatter = GlobalConfiguration.Configuration.Formatters.JsonFormatter; formatter.SerializerSettings = new JsonSerializerSettings {     Formatting = Formatting.Indented,     TypeNameHandling = TypeNameHandling.Objects,     ContractResolver = new CamelCasePropertyNamesContractResolver() }; 

When serializing object using the following code the global serializer settings are not used?

return new HttpResponseMessage(HttpStatusCode.OK) {     Content = new StringContent(JsonConvert.SerializeObject(page)) }; 

Isn't it possible to set the global serializer settings like this or am I missing something?

like image 228
marcus Avatar asked Feb 16 '14 18:02

marcus


2 Answers

Setting the JsonConvert.DefaultSettings did the trick.

JsonConvert.DefaultSettings = () => new JsonSerializerSettings {     Formatting = Formatting.Indented,     TypeNameHandling = TypeNameHandling.Objects,     ContractResolver = new CamelCasePropertyNamesContractResolver() }; 
like image 145
marcus Avatar answered Sep 23 '22 04:09

marcus


Accepted answer did not work for me. In .netcore, I got it working with...

services.AddMvc(c =>                  {                  ....                  }).AddJsonOptions(options => {                      options.SerializerSettings.Formatting = Formatting.Indented;                      ....                  }) 
like image 38
Michael Avatar answered Sep 20 '22 04:09

Michael