This 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.JsonSystem.Text.Jsonconverter for thePhoneNumbervalue object- Serializes
PhoneNumberas a JSON string in E.164 format - Deserializes from a JSON string to a
PhoneNumberinstance - Gracefully handles
nulland empty/whitespace JSON string values asnull - Convenient extension method
AddPhoneNumbersConvertersonJsonSerializerOptions
- Persist and exchange
PhoneNumbervalues as JSON with APIs - Use
PhoneNumberin your DTOs without custom mapping code - Share a consistent JSON representation (E.164) across microservices and clients
using 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);- JSON
nullis deserialized asnullPhoneNumber. - Empty or whitespace JSON strings are also deserialized as
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