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());
}
}
Then apply to your property as follows:
// 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; }
}
Or register the converter by adding it to the Converters
list in JsonSerializerOptions
services.AddControllers().AddJsonOptions(options =>
{
options.JsonSerializerOptions.Converters.Add(new LongToStringConverter());
});
Note: in .NET 5 and later, to make your converter handle null values override HandleNull
and return true
. In .NET Core 3 this was not possible.
System.Text.Json
– Facelifting