C#C
C#5mo ago
Piklo

source generated json serializer context with default property values

is there a way to make source generated json serializer context use default property values? or should i just give up and use constructors

using System.Text.Json;
using System.Text.Json.Serialization;

var json = "{\"Value2\": \"value from json string\"}";

var withDefaultsReflection = JsonSerializer.Deserialize<WithDefaults>(json);
Console.WriteLine($"\"{withDefaultsReflection!.Value ?? "null"}\", \"{withDefaultsReflection.Value2}\"");
// "value", "value from json string"

var withDefaults = JsonSerializer.Deserialize(json, WithDefaultsJsonSerializerContext.Default.WithDefaults);
Console.WriteLine($"\"{withDefaults!.Value ?? "null"}\", \"{withDefaults.Value2}\"");
// "null", "value from json string"

var withConstructor = JsonSerializer.Deserialize(json, WithConstructorJsonSerializerContext.Default.WithConstructor);
Console.WriteLine($"\"{withConstructor!.Value ?? "null"}\", \"{withConstructor.Value2}\"");
// "value", "value from json string"

public sealed class WithDefaults
{
    public string? Value { get; init; } = "value";
    public string Value2 { get; init; } = "value2";
}

[JsonSerializable(typeof(WithDefaults))]
public sealed partial class WithDefaultsJsonSerializerContext : JsonSerializerContext
{
}

public sealed class WithConstructor
{
    public string? Value { get; }
    public string Value2 { get; }
    public WithConstructor(string value = "value", string value2 = "value2")
    {
        Value = value;
        Value2 = value2;
    }
}

[JsonSerializable(typeof(WithConstructor))]
public sealed partial class WithConstructorJsonSerializerContext : JsonSerializerContext
{
}
Was this page helpful?