Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JsonConverter equivalent in using 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.

I migrated the properties from

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

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

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

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?

Thanks!

like image 537
Fritjof Berggren Avatar asked May 29 '19 12:05

Fritjof Berggren


People also ask

Which is better Newtonsoft JSON or System text JSON?

Json does case-insensitive property name matching by default. The System. Text. Json default is case-sensitive, which gives better performance since it's doing an exact match.

What is JsonConverter attribute?

The JsonConverterAttribute specifies which JsonConverter is used to convert an object. The attribute can be placed on a class or a member. When placed on a class, the JsonConverter specified by the attribute will be the default way of serializing that class.

How do I deserialize JSON?

A common way to deserialize JSON is to first create a class with properties and fields that represent one or more of the JSON properties. Then, to deserialize from a string or a file, call the JsonSerializer. Deserialize method.


2 Answers

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

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

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

Register the converter by adding it to the Converters list in JsonSerializerOptions

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

Note: The current release doesn't support nullable types yet.

like image 111
Mani Gandham Avatar answered Sep 17 '22 13:09

Mani Gandham


You can find the JsonConverterAttribute in the namespace System.Text.Json.Serialization.

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

like image 39
Lars Avatar answered Sep 19 '22 13:09

Lars