Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JsonSerializerSettings and Asp.Net Core

Trying to set JsonOutputFormatter options:

var jsonFormatter = (JsonOutputFormatter) options.OutputFormatters.FirstOrDefault(f => f is JsonOutputFormatter); if (jsonFormatter != null) {     jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); } 

or

mvcBuilder.AddJsonOptions(jsonOptions =>     {         jsonOptions.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();     }); 

But as soon as I add this, I get:

MissingMethodException: Method not found: 'Newtonsoft.Json.JsonSerializerSettings Microsoft.AspNet.Mvc.Formatters.JsonOutputFormatter.get_SerializerSettings()'.

I'm using the standard Microsoft.AspNet.Mvc.Formatters.Json (6.0.0-rc1-final)

Edit: Solved it by installing Newtonsoft.Json 6.0.6 (which downgrades all other references)

Anyone got that already? Thanks..

like image 985
Senj Avatar asked Mar 03 '16 12:03

Senj


People also ask

What is JsonSerializerOptions?

JsonSerializerOptions(JsonSerializerDefaults) Constructs a new JsonSerializerOptions instance with a predefined set of options determined by the specified JsonSerializerDefaults. JsonSerializerOptions(JsonSerializerOptions) Copies the options from a JsonSerializerOptions instance to a new instance.

What is JsonSerializerSettings?

Specifies the settings on a JsonSerializer object. Newtonsoft.Json. JsonSerializerSettings. Namespace: Newtonsoft.Json.

What is AddJsonOptions?

AddJsonOptions. This provides the means to configure the serailization settings and contract resolver which have already setup by calling .

What is CamelCasePropertyNamesContractResolver?

CamelCasePropertyNamesContractResolver. CamelCasePropertyNamesContractResolver inherits from DefaultContractResolver and simply overrides the JSON property name to be written in camelcase. ContractResolver.


1 Answers

.Net Core 1.0 RTM comes with CamelCase formatting out-of-the-box. This is a behavior change from RC2. However, if you need to modify it, try this snippet:

services.AddMvc()         .AddJsonOptions(opt =>     {         var resolver  = opt.SerializerSettings.ContractResolver;         if (resolver != null)         {             var res = resolver as DefaultContractResolver;             res.NamingStrategy = null;  // <<!-- this removes the camelcasing         }     }); 

More information here.

For dotnet core 1.0.1:

  services             .AddMvcCore()             .AddJsonFormatters(o => o...); 
like image 171
Jeson Martajaya Avatar answered Oct 04 '22 10:10

Jeson Martajaya