JsonConverter 相当于使用 System.Text.Json

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

我开始将 .net Core 3.0 应用程序中的一些代码从

Newtonsoft.Json
迁移到
System.Text.Json

我从

迁移了属性

[JsonProperty("id")]
[JsonPropertyName("id")]

但我有一些属性用

JsonConverter
属性装饰为:

[JsonConverter(typeof(DateTimeConverter))]
 [JsonPropertyName("birth_date")]
 DateTime BirthDate{ get; set; }

但是我在

System.Text.Json
中找不到与此 Newtonsoft 转换器等效的东西 有谁知道如何在 .net Core 3.0 中实现这一点吗?

谢谢!

c# json .net-core .net-core-3.0 system.text.json
2个回答
47
投票

System.Text.Json
现在支持 .NET 3.0 Preview-7 及更高版本中的自定义类型转换器。

您可以添加与类型匹配的转换器,并使用

JsonConverter
属性为属性使用特定转换器。

这里有一个

long
string
之间转换的示例(因为 javascript 不支持 64 位整数)。

public class LongToStringConverter : JsonConverter<long>
{
    public override long Read(ref Utf8JsonReader reader, Type type, JsonSerializerOptions options)
    {
        if (reader.TokenType == JsonTokenType.String)
        {
            // try to parse number directly from bytes
            ReadOnlySpan<byte> span = reader.HasValueSequence ? reader.ValueSequence.ToArray() : reader.ValueSpan;
            if (Utf8Parser.TryParse(span, out long number, out int bytesConsumed) && span.Length == bytesConsumed)
                return number;

            // try to parse from a string if the above failed, this covers cases with other escaped/UTF characters
            if (Int64.TryParse(reader.GetString(), out number))
                return number;
        }

        // fallback to default handling
        return reader.GetInt64();
    }

    public override void Write(Utf8JsonWriter writer, long value, JsonSerializerOptions options)
    {
        writer.WriteStringValue(value.ToString());
    }
}

然后按如下方式申请您的财产:

// Be sure not to use Newtonsoft.Json which also has a JsonConverter attribute
using System.Text.Json.Serialization;

public class Model
{
    [JsonConverter(typeof(LongToStringConverter))]
    public long MyProperty { get; set; }
}

或者通过将转换器添加到

Converters
 中的 
JsonSerializerOptions

列表来注册转换器
services.AddControllers().AddJsonOptions(options =>
{
    options.JsonSerializerOptions.Converters.Add(new LongToStringConverter());
});

注意:在 .NET 5 及更高版本中,要使转换器处理空值覆盖

HandleNull
并返回
true
。在 .NET Core 3 中,这是不可能的


4
投票

您可以在命名空间

JsonConverterAttribute
中找到
System.Text.Json.Serialization

https://learn.microsoft.com/en-us/dotnet/api/system.text.json.serialization.jsonconverterattribute?view=netcore-3.0

© www.soinside.com 2019 - 2024. All rights reserved.