System.Text.Json converter for the PhoneNumber value object, enabling seamless serialization and deserialization of phone numbers in E.164 format.
$ dotnet add package PosInformatique.Foundations.PhoneNumbers.JsonThis package provides System.Text.Json integration for the PhoneNumber value object
from PosInformatique.Foundations.PhoneNumbers.
It adds a JsonConverter<PhoneNumber> that serializes and deserializes phone numbers as JSON strings in E.164 format,
and an extension method to easily register the converter on your JsonSerializerOptions.
You can install the package from NuGet:
dotnet add package PosInformatique.Foundations.PhoneNumbers.Json
System.Text.Json converter for the PhoneNumber value objectPhoneNumber as a JSON string in E.164 formatPhoneNumber instancenull and empty/whitespace JSON string values as nullAddPhoneNumbersConverters on JsonSerializerOptionsPhoneNumber values as JSON with APIsPhoneNumber in your DTOs without custom mapping codeusing System.Text.Json;
using PosInformatique.Foundations.PhoneNumbers;
using PosInformatique.Foundations.PhoneNumbers.Json;
// Configure JsonSerializerOptions
var options = new JsonSerializerOptions()
.AddPhoneNumbersConverters();
using System.Text.Json;
using PosInformatique.Foundations.PhoneNumbers;
var options = new JsonSerializerOptions().AddPhoneNumbersConverters();
PhoneNumber phone = "+33123456789";
var json = JsonSerializer.Serialize(phone, options);
// json == "\"+33123456789\""
using System.Text.Json;
using PosInformatique.Foundations.PhoneNumbers;
var options = new JsonSerializerOptions().AddPhoneNumbersConverters();
var json = "\"+33123456789\"";
var phone = JsonSerializer.Deserialize<PhoneNumber>(json, options);
// phone represents "+33123456789"
using System.Text.Json;
using PosInformatique.Foundations.PhoneNumbers;
public sealed class ContactDto
{
public string Name { get; set; } = default!;
public PhoneNumber? Mobile { get; set; }
}
var options = new JsonSerializerOptions().AddPhoneNumbersConverters();
var contact = new ContactDto
{
Name = "John Doe",
Mobile = PhoneNumber.Parse("+33123456789")
};
var json = JsonSerializer.Serialize(contact, options);
// {
// "Name": "John Doe",
// "Mobile": "+33123456789"
// }
var deserialized = JsonSerializer.Deserialize<ContactDto>(json, options);
null is deserialized as null PhoneNumber.null.var options = new JsonSerializerOptions().AddPhoneNumbersConverters();
var jsonNull = "null";
var phoneNull = JsonSerializer.Deserialize<PhoneNumber?>(jsonNull, options); // null
var jsonEmpty = "\"\"";
var phoneEmpty = JsonSerializer.Deserialize<PhoneNumber?>(jsonEmpty, options); // null