如何将集合序列化为 Json 但在每个实例之前使用 class 名称

How to Serialize Collection to Json but with class name preceding each instance

我的 ASP.Net 核心 3.1 应用程序中有以下 Class 结构:

public class EmailModel
{
    public string Subject { get; set; }
    public BodyModel Body { get; set; }
    public List<EmailAddress> ToRecipients { get; set; }
}

public class EmailAddress
{
    public string Name { get; set; }
    public string Address { get; set; }
}

序列化如下:

{
    "subject": "tba",
    "body": {
        "contentType": "html",
        "content": "the content"
    },
    "toRecipients": [
        {
            "name": "",
            "address": "name1@example.com"
        },
        {
            "name": "",
            "address": "name2@example.com"
        }
    ]
}

但我需要它序列化的是以下内容(每个 emailAddress 元素都已命名):

{
    "subject": "tba",
    "body": {
        "contentType": "html",
        "content": "the content"
    },
    "toRecipients": [
        {
            "emailAddress": {
                "name": "",
                "address": "name1@example.com"
            }
        },
        {
            "emailAddress": {
                "name": "",
                "address": "name2@example.com"
            }
        }
    ]
}

我怎样才能做到这一点(我很乐意使用 System.Text.JsonNewtonsoft,以更容易的为准)

根据@Andy 的建议,考虑只使用一个反映 Json 的模型,因为这样会更直观。

否则,使用 Newtonsoft.Json,您可以使用 JsonPropertyAttribute attribute with ItemConverterType property. And implementing a custom JsonConverter class 自定义集合元素的序列化,例如:

public class EmailModel
{
    public string Subject { get; set; }
    public BodyModel Body { get; set; }

    [JsonProperty(ItemConverterType = typeof(NestingEmailAddressConverter))]
    public List<EmailAddress> ToRecipients { get; set; }
}

public class NestingEmailAddressConverter : JsonConverter
{
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        JObject o = new JObject();
        o.Add("emailAddress", JToken.FromObject(value));
        o.WriteTo(writer);
    }

    public override bool CanConvert(Type objectType)
    {
        return objectType == typeof(EmailAddress);
    }

    public override bool CanRead => false;

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        => throw new NotImplementedException();
}

调用为 Console.WriteLine(JsonConvert.SerializeObject(model, Formatting.Indented)); 生成目标 Json。