JsonConverter 等效于使用 System.Text.Json [英] JsonConverter equivalent in using System.Text.Json

查看:32
本文介绍了JsonConverter 等效于使用 System.Text.Json的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开始将一些代码从 Newtonsoft.Json 迁移到 .net Core 3.0 应用程序中的 System.Text.Json.

I'm starting to migrate some code I have from Newtonsoft.Json to System.Text.Json in a .net Core 3.0 app.

我从

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

但我有一些用 JsonConverter 属性修饰的属性:

but I have some properties decorated with the JsonConverter attribute as:

[JsonConverter(typeof(DateTimeConverter))][JsonPropertyName("birth_date")]日期时间出生日期{获取;放;}

但是我在 System.Text.Json 中找不到这个 Newtonsoft 转换器的等效项有人知道如何在 .net Core 3.0 中实现吗?

But I cannot find the equivalent of this Newtonsoft converter in System.Text.Json Does someone know how can this be achieved in .net Core 3.0?

谢谢!

推荐答案

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

System.Text.Json now supports custom type converters in .NET 3.0 preview-7 and above.

您可以添加与类型匹配的转换器,并使用 JsonConverter 属性来为属性使用特定的转换器.

You can add converters that match on type, and use the JsonConverter attribute to use a specific converter for a property.

这是在 longstring 之间转换的示例(因为 javascript 不支持 64 位整数).

Here's an example to convert between long and string (because javascript doesn't support 64-bit integers).

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());
    }
}

通过将转换器添加到 JsonSerializerOptions

services.AddControllers().AddJsonOptions(options =>
{
    options.JsonSerializerOptions.Converters.Add(new LongToStringConverter());
});

注意:当前版本还不支持可为空类型.

这篇关于JsonConverter 等效于使用 System.Text.Json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆