2

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?

1

2 Answers 2

6

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);
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.