Skip to content

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
# Conflicts:
#	InertiaCore/Response.cs
#	InertiaCore/ResponseFactory.cs
#	README.md
@kapi2289 kapi2289 force-pushed the custom-json-serializer branch from 5e8b5be to 66a6471 Compare November 9, 2025 08:21
@kapi2289 kapi2289 merged commit f39a6e6 into v1 Nov 9, 2025
1 check passed
@kapi2289 kapi2289 deleted the custom-json-serializer branch November 9, 2025 08:23
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

2 participants