Skip to content
This repository was archived by the owner on Jul 29, 2026. It is now read-only.

Repository files navigation

Winton.Extensions.Serialization.Json

AppveyorTravis CINuGet versionNuGet version

Implementations of JsonConverter providing useful serialization overrides.

Converters

SingleValueConverter

A converter for serializing types with a single backing field as the value of that field, and deserializing back to the original type. This can be useful, for example, when using strong typed IDs. Consider a simple AccountId type

publicstructAccountId:IEquatable<AccountId>{privatereadonlystring_value;publicAccountId(stringvalue){_value=value;}publicstaticexplicitoperatorstring(AccountIdid){returnid._value;}publicstaticexplicitoperatorAccountId(stringvalue){returnnewAccountId(value);}publicstaticbooloperator==(AccountIdleft,AccountIdright){returnleft.Equals(right);}publicstaticbooloperator!=(AccountIdleft,AccountIdright){return!left.Equals(right);}publicboolEquals(AccountIdother){returnstring.Equals(_value,other._value);}publicoverrideboolEquals(objectobj){if(objisnull){returnfalse;}returnobjisAccountIdid&&Equals(id);}publicoverrideintGetHashCode(){return_value?.GetHashCode()??0;}publicoverridestringToString(){return_value;}}

which is simply a strong typed wrapper around a string, providing expected cast, equality, and formatting members. It could be used, for example, on an Account type, say

publicsealedclassAccount{publicAccount(AccountIdid,AccountNamename,
...){AccountId=id,
Name =name;
...}publicAccountIdId{get;}publicAccountNameName{get;}
...}

to ensure that the AccountId and AccountName (which is presumably also string-like) could never be mixed up. However, since these wrapper types do not expose any public properties, by default they would serialize as empty objects, and the Account would always serialize as

{
"accountId": {},
"accountName": {},
...
}

then deserialize as default values. Simply adding a JsonConverter attribute of type SingleValueConverter to the AccountId type (and similar for the AccountName), like so

[JsonConverter(typeof(SingleValueConverter))]publicstructAccountId:IEquatable<AccountId>{
...}

will fix this issue, and cause the strong typed fields to serialize and deserialize as desired, such as

{
"accountId": "AZ001",
"accountName": "WXX",
...
}

About

A library containing useful JSON serialization classes

Topics

Resources

Contributing

Stars

1 star

Watchers

3 watching

Forks

Releases

Packages

Used by

Contributors

Languages