Create Custom DictionaryConverter for JSON Serialization
In this article, we shall create a custom DictionaryInt32Converter for int32 or enum as keys for JSON serialization using C# .NET example.
As we know the new .NET /ASP.NET Core 3.1 onward framework has removed the dependency on JSON.NET and uses its own JSON serializer i.e. ‘System.Text.Json‘.
Being lightweight for any custom serialization, you need to add a Custom converter.
We shall be following below high-level steps to create a custom converter using a basic pattern,
Dictionary Support in System.Text.JSON
System.Text.Json has built-in support for only Dictionary types that matches Dictionary< string, TValue>.
That’s means if the Key value is non-string like Int32 or Enum then serialization will throw NotSupportedException.
Supporting Dictionary with non-string key
To allow non-string key serialization, please create the custom DictionaryConverter as a serializer option.
Today we shall try how to create simple DictionaryInt32Converter supporting Dictionary< Int32, TValue>.
Create a Custom DictionaryInt32Converter
Create a Custom Converter class derived from JsonConverter<T>.
Here T is the type a type of Dictionary< Int32, TValue> to be serialized and deserialized.
Lets create a class from a type that is required,
public class DictionaryInt32Converter : JsonConverter<Dictionary<int, string>> { . . }
Override the Read method
Let’s add below two overrides Read /Write methods as below,
public override Dictionary<int, string> Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { if (reader.TokenType != JsonTokenType.StartObject) { throw new JsonException(); } var value = new Dictionary<int, string>(); while (reader.Read()) { if (reader.TokenType == JsonTokenType.EndObject) { return value; } string keyString = reader.GetString(); if (!int.TryParse(keyString, out int keyAsInt32)) { throw new JsonException($"Unable to convert \"{keyString}\" to System.Int32."); } reader.Read(); string itemValue = reader.GetString(); value.Add(keyAsInt32, itemValue); } throw new JsonException("Error Occured"); }
Override the Write method
Please see below Overridden Write method,
public override void Write(Utf8JsonWriter writer, Dictionary<int, string> value, JsonSerializerOptions options) { writer.WriteStartObject(); foreach (KeyValuePair<int, string> item in value) { writer.WriteString(item.Key.ToString(), item.Value); } writer.WriteEndObject(); }
Perform serialize/deserialize
Let’s pass key as int32 in the dictionary,
Dictionary<int, string> dictEmployess = new Dictionary<int, string>();
Use JsonSerializerOptions to register the custom converter,
Finally JSON serialization is successful.
Please bookmark this page and share it with your friends. Please Subscribe to the blog to receive notifications on freshly published(2024) best practices and guidelines for software design and development.
Thanks for writing this – super useful!