Jay
Jay

Reputation: 2244

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?

Upvotes: 2

Views: 3303

Answers (2)

Dark Daskin
Dark Daskin

Reputation: 1474

If you want to ensure that you use the same serializer options as ASP.NET Core, you can inject the options object to your service as follows:

using System.Text.Json;
using Microsoft.AspNetCore.Http.Json;
using Microsoft.Extensions.Options;

class MyService
{
    private readonly JsonSerializerOptions _jsonSerializerOptions;

    public MyService(IOptions<JsonOptions> jsonOptions)
    {
        _jsonSerializerOptions = jsonOptions.Value.SerializerOptions;
    }

    public void MyMethod()
    {
        var data = new { Foo = "bar" };
        var json = JsonSerializer.Serialize(data, _jsonSerializerOptions);
    }
}

Upvotes: 0

Emilien Mathieu
Emilien Mathieu

Reputation: 351

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);

Upvotes: 6

Related Questions