Skip to content
Martijn Bodeman edited this page Oct 2, 2024 · 8 revisions

The Iban type supports serialization to and from JSON. This allows the type to be used directly in your models/DTO/API contracts (versus using the string type), while retaining the ability to be represented in JSON correctly.

  • When deserializing from string to Iban, validation occurs automatically.
  • When serializing from Iban to string, the value is formatted using the Electronic format.

System.Text.Json

IbanNet comes with built-in support for System.Text.Json to serialize/deserialize the Iban type to and from JSON.

All target frameworks from .NET Standard 2.1 and .NET 6.0 and up are supported. IbanNet targetting .NET Framework 4.x and .NET Standard 2.0 does not support JSON conversion via STJ out of the box.

Example

public record Payment(Iban BankAccountNumber, decimal Amount) { }

IIbanParser parser = ..; // Dependency injection

Payment payment1 = new Payment(parser.Parse("NL91 ABNA 0417 1643 00"), 100M);
string json = System.Text.Json.JsonSerializer.Serialize(payment1);

// Produces: {"BankAccountNumber":"NL91ABNA0417164300","Amount":100}

Payment payment2 = System.Text.Json.JsonSerializer.Deserialize<Payment>(json);
bool isSame = payment2.Equals(payment1); // true

Newtonsoft.Json / JSON.NET

JSON.NET has type converter support and as such - to avoid a dependency on the Newtonsoft library - IbanNet does not provide a dedicated JsonConverter. Instead, for conversion the provided type converter will be used, requiring no additional setup or configuration.

Example

public record Payment(Iban BankAccountNumber, decimal Amount) { }

IIbanParser parser = ..; // Dependency injection

Payment payment1 = new Payment(parser.Parse("NL91 ABNA 0417 1643 00"), 100M);
string json = JsonConvert.SerializeObject(payment1);

// Produces: {"BankAccountNumber":"NL91ABNA0417164300","Amount":100}

Payment payment2 = JsonConvert.DeserializeObject<Payment>(json);
bool isSame = payment2.Equals(payment1); // true

Caveat

Note that if no dependency injection is used (for both variants of JSON support), internally IbanNet will use the Iban.Validator instance. If you have customized the IbanValidator options (eg. custom rules, or different registry provider), you must also set the static validator instance to allow the JSON deserializer to pick up the specific validator instance. This is a deprecated mechanism and may be removed in the future, thus, depending on this form of JSON support may then break. Therefor it is recommended to use dependency injection instead at all times so that you do not worry about this.