Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[1.x] Add custom JSON serializer #27

Open
wants to merge 3 commits into
base: v1
Choose a base branch
from
Open

Conversation

kapi2289
Copy link
Owner

@kapi2289 kapi2289 commented Jan 3, 2025

Resolves #21. @Naamloos, please let me know if this implementation solves your issue.

You can use a custom JSON serializer in your app by creating a custom class implementing the IInertiaSerializer
interface:

using System.Text.Json;
using System.Text.Json.Serialization;
using Microsoft.AspNetCore.Mvc;

public class CustomSerializer : IInertiaSerializer
{
    // Used in HTML responses
    public string Serialize(object? obj)
    {
        // Default serialization
        return JsonSerializer.Serialize(obj, new JsonSerializerOptions
        {
            PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
            ReferenceHandler = ReferenceHandler.IgnoreCycles
        });
    }

    // Used in JSON responses
    public JsonResult SerializeResult(object? obj)
    {
        // Default serialization
        return new JsonResult(obj, new JsonSerializerOptions
        {
            PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
            ReferenceHandler = ReferenceHandler.IgnoreCycles
        });
    }
}

or extending the DefaultInertiaSerializer class, which also implements the IInertiaSerializer interface:

public class CustomSerializer : DefaultInertiaSerializer
{
    protected new static JsonSerializerOptions GetOptions()
    {
        // Default options
        return new JsonSerializerOptions
        {
            PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
            ReferenceHandler = ReferenceHandler.IgnoreCycles
        };
    }
}

You can then register it in the configuration:

builder.Services.AddInertia();

[...]

builder.Services.UseInertiaSerializer<CustomSerializer>();

[...]

app.UseInertia();

@kapi2289 kapi2289 linked an issue Jan 4, 2025 that may be closed by this pull request
@kapi2289 kapi2289 added this to the v1.0.0 milestone Jan 4, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Configuring JSON Serializer
1 participant