反序列化时为缺失的 JSON 属性提供默认值

问题描述 投票:0回答:1

我有这样的示例 JSON:

                        {
                            "Type": "Service",
                            "Uid": "Bridge 1",
                            "ServiceName": "Bridge 1"
                        }

我将其反序列化为如下类:

public record ServiceConfig
{
    public required string Type { get; init; }
    public required string Uid { get; init; }
    public required string ServiceName { get; init; }
}

var cfg = System.Text.Json.JsonSerializer.Deserialize<ServiceConfig>(stream);

我希望

ServiceName
在 JSON 中是可选的,当未提供时,将使用
Uid
值,以便以下两个 JSON 产生相同的结果:

                        {
                            "Type": "Service",
                            "Uid": "Bridge 1",
                            "ServiceName": "Bridge 1"
                        },
                        {
                            "Type": "Service",
                            "Uid": "Bridge 1"
                        },

有没有一种简单的方法可以做到这一点,而无需手动解析 JSON DOM,而不是使用自动反序列化?

c# .net .net-8.0
1个回答
0
投票

您可以在

ServiceName
属性中实现一些逻辑

public record ServiceConfig
{
    public required string Type { get; init; }
    public required string Uid { get; init; }

    private string _serviceName;
    public required string ServiceName {
        get => _serviceName ?? Uid; // Returns Uid is _serviceName is null.
        init => _serviceName = value;
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.