使用System.Text.Json的JsonConverter等效项

编程入门 行业动态 更新时间:2024-10-26 18:17:27
本文介绍了使用System.Text.Json的JsonConverter等效项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我开始将已有的某些代码从 Newtonsoft.Json 迁移到 System.Text.Json Core 3.0应用。

I'm starting to migrate some code I have from Newtonsoft.Json to System.Text.Json in a 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)] DateTime BirthDate {get;组; }

但是我在 System.Text.Json 有人知道如何在 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 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.

下面是在 long 和 string 之间进行转换的示例(因为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()); } }

通过将转换器添加到<$ c中进行注册 JsonSerializerOptions

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

注意:当前版本尚不支持可空类型。

更多推荐

使用System.Text.Json的JsonConverter等效项

本文发布于:2023-11-03 13:06:27,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1555206.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Text   System   JsonConverter   Json

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!