C#C
C#4y ago
Arkobat

Custom JSON serializer not working

Hello
I have a custom serializer i cannot get to work.
When I use the model in a controller, it just gives me null.

It is the following class I try to serialize
public class ExternalId
{
    public string Id { get; set; }
}

I want to be able to use the following input
{
    "id1": "a",
    "id2": "b",
    "id3": "3"
}
// to e.g. this class
public class MyDTO {
    public ExternalId Id1 {get; set;}
    public ExternalId Id2 {get; set;}
    public ExternalId Id3 {get; set;}
}

This is my serializer.
Is should just take the string, and wrap it in a ExternalId
I have tried to put break points in here also, but they are never reached
public class ExternalIdSerializer : JsonConverter<ExternalId>
{
    public override ExternalId? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
    {
        return reader.GetString() is null
            ? null
            : new ExternalId(reader.GetString()!);
    }

    public override void Write(Utf8JsonWriter writer, ExternalId externalId, JsonSerializerOptions options)
    {
        writer.WriteStringValue(externalId.Id);
    }
}

And last, this is where I add my serializer
services
    .AddControllers()
    .AddJsonOptions(options =>
    {
        options.JsonSerializerOptions.PropertyNameCaseInsensitive = true;
        
        var converters = options.JsonSerializerOptions.Converters;
        converters.Add(new JsonStringEnumConverter());
        converters.Add(new ExternalIdSerializer());
    });
Was this page helpful?