I have an ASP.NET Core 8 controller.
When I return an object serialized using Newtonsoft.Json
in the Ok
return below, it changes the properties to lower case in the JSON.
I want them to stay as declared in C# without having to put JsonPropertyName
attribute on all the properties.
Instead of this:
{
"id":"0",
"name": "Foo"
}
I want to get this representation instead:
{ "Id: "0", "Name": "Foo" }
This is the C# class for this:
class Foo
{
public string Id { get; set; }
public string Name { get; set; }
}
/// </summary>
[ApiController]
public class ManagerApiController : ControllerBase
{
[Route("/api/v1/search-approval-workflows")]
[ValidateModelState]
[SwaggerOperation("SearchApprovalWorkflowsGet")]
public virtual IActionResult SearchApprovalWorkflowsGet([FromQuery] string s)
{
// ...
return OK(foo);
}
}
I tried
DefaultContractResolver resolver =
new DefaultContractResolver
{
NamingStrategy = new DefaultNamingStrategy()
};
resolver.NamingStrategy.OverrideSpecifiedNames = false;
string json = JsonConvert.SerializeObject(obj, new JsonSerializerSettings
{
ContractResolver = resolver,
Formatting = Formatting.Indented
});
return json;
But that didn't work.
I also tried returning new JsonResult(foo)
, but again without luck.
Thanks PowerMouse.
This was it. Example shows for json.net and newtonsoft, maybe only one needed depending on what is used.
services
.AddMvc().AddJsonOptions( jsonOpt =>
{
jsonOpt.JsonSerializerOptions.PropertyNamingPolicy = null;
})
.AddNewtonsoftJson(opts =>
{
opts.SerializerSettings.ContractResolver = null;
})