本文主要介绍.NET Core(C#)中,使用System.Text.Json时,编写自定义转换器JsonConverter及获取属性名的方法,以及相关的示例代码。

1、自定义的实例类

public class MyMailContent
{
public string Name { get; set; }
public string Subject { get; set; }
public string Body { get; set; }
}

2、自定义转换器JsonConverter

public class MyMailContentJsonConverter : JsonConverter<MyMailContent>
{
    public override MyMailContent Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
    {
        if (reader.TokenType != JsonTokenType.StartObject)
        {
            throw new JsonException();
        }
        var mailContent = new MyMailContent();
        while (reader.Read())
        {
            if (reader.TokenType == JsonTokenType.EndObject)
            {
                return mailContent;
            }
            if (reader.TokenType == JsonTokenType.PropertyName)
            {
                var propertyName = reader.GetString();
                reader.Read();
                switch (propertyName)
                {
                    case "Name":
                        mailContent.Name = reader.GetString();
                        break;
                    case "Subject":
                        mailContent.Subject = reader.GetString();
                        break;
                    case "Body":
                        string body = reader.GetString();
                        //body的内容做一些处理
                        mailContent.Body = body;
                        break;
                }
            }
        }
        throw new JsonException();
    }
    public override void Write(Utf8JsonWriter writer, MyMailContent mailcontent, JsonSerializerOptions options)
    {
        throw new NotImplementedException();
    }
}
private static JsonSerializerOptions _jsonDeserializeOptions = new()
{
    ReadCommentHandling = JsonCommentHandling.Skip,
    AllowTrailingCommas = true,
    Converters =
    {
        new MyMailContentJsonConverter()
    }
};

3、使用自定义转换器

var jsonstring = JsonSerializer.Serialize(new MyMailContent
{
Name = "邮件",
Subject = "自定义转换器写法",
Body = "邮件内容"
});
var MailContent = JsonSerializer.Deserialize<MyMailContent>(jsonstring, _jsonDeserializeOptions);

推荐文档