Search code examples
c#asp.net-coresystem.text.jsonjsonserializerasp.net-core-6.0

How to serialize object in ASP.NET Core/6 using a camelCase?


When using ASP.NET Core/6 to return an object as JSON we use return Ok(data) which takes the data object and serializes it using camelCase.

But, when I want to serialize an object manually, it does not serialize using camelCase.

Here is how I am attempting to decentralize the object

System.Text.Json.JsonSerializer.Serialize(data)

Is there a service to use in ASP.NET Core that would serialize the object using the default formatter? If not, how can I serialize using camelCase?


Solution

  • You can use the object: JsonSerializerOptions. You have to pass it as a parameter after your object like this:

    JsonSerializerOptions options = new JsonSerializerOptions()
    {
        PropertyNamingPolicy = JsonNamingPolicy.CamelCase
    };
    
    System.Text.Json.JsonSerializer.Serialize(data, options);