C# System.Text.Json:如何将对象序列化为带有键的嵌套子对象?

C# System.Text.Json:如何将对象序列化为带有键的嵌套子对象?,c#,json,.net,system.text.json,C#,Json,.net,System.text.json,我有一个要序列化的以下类的对象: [Serializable] public class BuildInfo { public DateTime BuildDate { get; set; } public string BuildVersion { get; set; } } 我编写了以下方法来序列化任何对象: ... public static string JsonSerialize<TValue>(TValue value) { var optio

我有一个要序列化的以下类的对象:

[Serializable]
public class BuildInfo
{
    public DateTime BuildDate { get; set; }

    public string BuildVersion { get; set; }
}
我编写了以下方法来序列化任何对象:

...
public static string JsonSerialize<TValue>(TValue value)
{
    var options = new JsonSerializerOptions
    {

        PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
        WriteIndented = true
    };

    return JsonSerializer.Serialize(value, options);
}
...
我希望得到如下输出:

{
    "buildInfo": {
        "buildDate": "2021-04-22T17:29:59.1611109+03:00",
        "buildVersion": "1.0.1"
    }
}
我怎么做?你可以试试这个

JsonSerialize( new { BuildInfo = build })
编辑

处理此问题的简单方法是在调用JsonSerialize之前使用包装器类

var buildInfoWrapper = new { BuildInfo = buildInfo };
JsonSerialize(buildInfoWrapper)
你可以试试这个

JsonSerialize( new { BuildInfo = build })
编辑

处理此问题的简单方法是在调用JsonSerialize之前使用包装器类

var buildInfoWrapper = new { BuildInfo = buildInfo };
JsonSerialize(buildInfoWrapper)

我花了半天时间,但我做到了

首先,我们需要定义自定义JSON转换器:

public class TopAsNestedJsonConverter<TValue> : JsonConverter<TValue>
{
    private readonly string _propertyName;

    private readonly JsonSerializerOptions _referenceOptions;

    public TopAsNestedJsonConverter(JsonSerializerOptions referenceOptions)
    {
        _propertyName = FormatPropertyName(typeof(TValue).Name, referenceOptions);
        _referenceOptions = referenceOptions;
    }

    public override TValue? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
    {
        var value = default(TValue);
        var propertyFound = false;

        if (reader.TokenType != JsonTokenType.StartObject)
        {
            return value;
        }

        while (reader.Read())
        {
            switch (reader.TokenType)
            {
                case JsonTokenType.PropertyName when IsPropertyFound(reader.GetString()):
                    propertyFound = true;
                    break;
                case JsonTokenType.StartObject when propertyFound:
                    value = JsonSerializer.Deserialize<TValue>(ref reader, _referenceOptions);
                    propertyFound = false;
                    break;
            }
        }

        return value;
    }

    public override void Write(Utf8JsonWriter writer, TValue? value, JsonSerializerOptions options)
    {
        writer.WriteStartObject();
        writer.WritePropertyName(_propertyName);
        JsonSerializer.Serialize(writer, value, _referenceOptions);
        writer.WriteEndObject();
    }

    private bool IsPropertyFound(string? propertyName)
    {
        return string.Equals(_propertyName, propertyName,
            _referenceOptions.PropertyNameCaseInsensitive
                ? StringComparison.OrdinalIgnoreCase
                : StringComparison.Ordinal);
    }

    private static string FormatPropertyName(string propertyName, JsonSerializerOptions options)
    {
        return options.PropertyNamingPolicy != null
            ? options.PropertyNamingPolicy.ConvertName(propertyName)
            : propertyName;
    }
}
公共类TopAsNestedJsonConverter:JsonConverter
{
私有只读字符串_propertyName;
私有只读JSONSerializeProptions\u引用选项;
公共TopAsNestedJsonConverter(JsonSerializerOptions引用选项)
{
_propertyName=FormatPropertyName(typeof(TValue).Name,referenceOptions);
_referenceOptions=referenceOptions;
}
公共覆盖TValue?读取(参考Utf8JsonReader reader,键入typeToConvert,JsonSerializerOptions选项)
{
var值=默认值(TValue);
var propertyFound=false;
if(reader.TokenType!=JsonTokenType.StartObject)
{
返回值;
}
while(reader.Read())
{
开关(reader.TokenType)
{
IsPropertyFound(reader.GetString())时的JsonTokenType.PropertyName案例:
propertyFound=true;
打破
当找到属性时,案例JsonTokenType.StartObject:
value=JsonSerializer.Deserialize(ref-reader,_-referenceOptions);
propertyFound=false;
打破
}
}
返回值;
}
公共重写无效写入(Utf8JsonWriter写入程序、TValue?值、JsonSerializerOptions选项)
{
writer.WriteStartObject();
writer.WritePropertyName(_propertyName);
序列化(writer、value、_referenceOptions);
writer.WriteEndObject();
}
私有bool IsPropertyFound(字符串?propertyName)
{
返回字符串.Equals(_propertyName,propertyName,
_referenceOptions.PropertyNameCase不敏感
?StringComparison.OrdinalIgnoreCase
:StringComparison.序数);
}
私有静态字符串FormatPropertyName(字符串propertyName、JsonSerializerOptions选项)
{
return options.PropertyNamingPolicy!=null
?options.PropertyNamePolicy.ConvertName(propertyName)
:propertyName;
}
}
然后,我们需要一个实用程序类以便于使用:

public static class JsonUtilities
{
    public static string JsonSerializeTopAsNested<TValue>(TValue? value, JsonSerializerOptions? options = null)
    {
        return JsonSerializer.Serialize(value, GetConverterOptions<TValue>(options));
    }

    public static async Task<string> JsonSerializeTopAsNestedAsync<TValue>(TValue? value,
        JsonSerializerOptions? options = null, CancellationToken cancellationToken = default)
    {
        await using var stream = new MemoryStream();
        await JsonSerializer.SerializeAsync(stream, value, GetConverterOptions<TValue>(options), cancellationToken);
        return Encoding.UTF8.GetString(stream.ToArray());
    }

    public static TValue? JsonDeserializeTopAsNested<TValue>(string json, JsonSerializerOptions? options)
    {
        return JsonSerializer.Deserialize<TValue>(json, GetConverterOptions<TValue>(options));
    }

    public static async Task<TValue?> JsonDeserializeTopAsNestedAsync<TValue>(string json,
        JsonSerializerOptions? options, CancellationToken cancellationToken = default)
    {
        await using var stream = new MemoryStream(Encoding.UTF8.GetBytes(json));
        return await JsonSerializer.DeserializeAsync<TValue>(stream, GetConverterOptions<TValue>(options),
            cancellationToken);
    }

    private static JsonSerializerOptions GetConverterOptions<TValue>(JsonSerializerOptions? options = null)
    {
        var referenceOptions = options == null ? new JsonSerializerOptions() : new JsonSerializerOptions(options);
        var converterOptions = new JsonSerializerOptions(referenceOptions);
        converterOptions.Converters.Add(new TopAsNestedJsonConverter<TValue>(referenceOptions));

        return converterOptions;
    }
}
公共静态类JsonUtilities
{
公共静态字符串JsonSerializeTopAsNested(TValue?值,JSONSerializeProptions?选项=null)
{
返回JsonSerializer.Serialize(值,GetConverterOptions(选项));
}
公共静态异步任务JsonSerializeTopAsNestedAsync(TValue?值,
JsonSerializerOptions?选项=null,取消令牌取消令牌=default)
{
使用var stream=newmemoryStream()等待;
等待JsonSerializer.SerializeAsync(流、值、GetConverterOptions(选项)、cancellationToken);
返回Encoding.UTF8.GetString(stream.ToArray());
}
公共静态TValue?JsonDeserializeTopAsNested(字符串json、JsonSerializerOptions?选项)
{
返回JsonSerializer.Deserialize(json,GetConverterOptions(options));
}
公共静态异步任务JsonDeserializeTopAsNestedAsync(字符串json,
JsonSerializerOptions?选项,CancellationToken CancellationToken=默认值)
{
等待使用var stream=newmemoryStream(Encoding.UTF8.GetBytes(json));
return wait JsonSerializer.DeserializeAsync(流、GetConverterOptions(选项),
取消令牌);
}
私有静态JsonSerializerOptions GetConverterOptions(JsonSerializerOptions?选项=null)
{
var referenceOptions=options==null?新建JsonSerializerOptions():新建JsonSerializerOptions(选项);
var converterOptions=新JsonSerializerOptions(参考选项);
converterOptions.Converters.Add(新TopAsNestedJsonConverter(referenceOptions));
返回转换器选项;
}
}
最后,示例代码:

public class BuildInfo
{
    public DateTime? BuildDate { get; init; }

    public string? BuildVersion { get; init; }
}

public static class Program
{
    public static async Task Main()
    {
        var buildInfo = new BuildInfo
        {
            BuildDate = DateTime.Now,
            BuildVersion = "1.0.1"
        };

        var options = new JsonSerializerOptions(JsonSerializerDefaults.Web)
        {
            PropertyNameCaseInsensitive = false,
            WriteIndented = true
        };

        var json = await JsonUtilities.JsonSerializeTopAsNestedAsync(buildInfo, options);

        Console.WriteLine(json);

        var info = await JsonUtilities.JsonDeserializeTopAsNestedAsync<BuildInfo>(json, options);

        Console.WriteLine($"{info?.BuildDate} {info?.BuildVersion}");
    }
}
公共类BuildInfo
{
public DateTime?BuildDate{get;init;}
公共字符串?BuildVersion{get;init;}
}
公共静态类程序
{
公共静态异步任务Main()
{
var buildInfo=新建buildInfo
{
BuildDate=DateTime。现在,
BuildVersion=“1.0.1”
};
var options=newJSONSerializedRoptions(JsonSerializerDefaults.Web)
{
PropertyNameCaseSensitive=false,
WriteIndended=true
};
var json=await JsonUtilities.JsonSerializeTopAsNestedAsync(buildInfo,options);
Console.WriteLine(json);
var info=await JsonUtilities.JsonDeserializeTopAsNestedAsync(json,选项);
Console.WriteLine($“{info?.BuildDate}{info?.BuildVersion}”);
}
}

如果您在代码或算法本身中发现任何错误,我将非常高兴。

我花了半天时间,但我做到了

首先,我们需要定义自定义JSON转换器:

public class TopAsNestedJsonConverter<TValue> : JsonConverter<TValue>
{
    private readonly string _propertyName;

    private readonly JsonSerializerOptions _referenceOptions;

    public TopAsNestedJsonConverter(JsonSerializerOptions referenceOptions)
    {
        _propertyName = FormatPropertyName(typeof(TValue).Name, referenceOptions);
        _referenceOptions = referenceOptions;
    }

    public override TValue? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
    {
        var value = default(TValue);
        var propertyFound = false;

        if (reader.TokenType != JsonTokenType.StartObject)
        {
            return value;
        }

        while (reader.Read())
        {
            switch (reader.TokenType)
            {
                case JsonTokenType.PropertyName when IsPropertyFound(reader.GetString()):
                    propertyFound = true;
                    break;
                case JsonTokenType.StartObject when propertyFound:
                    value = JsonSerializer.Deserialize<TValue>(ref reader, _referenceOptions);
                    propertyFound = false;
                    break;
            }
        }

        return value;
    }

    public override void Write(Utf8JsonWriter writer, TValue? value, JsonSerializerOptions options)
    {
        writer.WriteStartObject();
        writer.WritePropertyName(_propertyName);
        JsonSerializer.Serialize(writer, value, _referenceOptions);
        writer.WriteEndObject();
    }

    private bool IsPropertyFound(string? propertyName)
    {
        return string.Equals(_propertyName, propertyName,
            _referenceOptions.PropertyNameCaseInsensitive
                ? StringComparison.OrdinalIgnoreCase
                : StringComparison.Ordinal);
    }

    private static string FormatPropertyName(string propertyName, JsonSerializerOptions options)
    {
        return options.PropertyNamingPolicy != null
            ? options.PropertyNamingPolicy.ConvertName(propertyName)
            : propertyName;
    }
}
公共类TopAsNestedJsonConverter:JsonConverter
{
私有只读字符串_propertyName;
私有只读JSONSerializeProptions\u引用选项;
公共TopAsNestedJsonConverter(JsonSerializerOptions引用选项)
{
_propertyName=FormatPropertyName(typeof(TValue).Name,referenceOptions);
_referenceOptions=referenceOptions;
}
公共覆盖TValue?读取(参考Utf8JsonReader reader,键入typeToConvert,JsonSerializerOptions选项)
{
var值=默认值(TValue);
var propertyFound=false;
if(reader.TokenT