Skip to content

Instantly share code, notes, and snippets.

@algonzalez
Created March 2, 2021 04:17
Show Gist options
  • Save algonzalez/cc9081a8ab99409046f17296ae057c78 to your computer and use it in GitHub Desktop.
Save algonzalez/cc9081a8ab99409046f17296ae057c78 to your computer and use it in GitHub Desktop.
/// <summary>
/// Initial attempt at a simple <see cref="System.Text.Json.Serialization.JsonConverter"/>
/// that handles conversion between objects and interfaces.
/// <p>
/// Appears to fix the loss of interface typed values during serialization,
/// as well as the "Deserialization of interface types is not supported" exception.</p>
/// </summary>
/// <example>
/// // Register the converter with a <see cref="System.Text.Json.JsonSerializerOptions"/> instance:
/// <pre><code>var converter = new ObjectInterfaceJsonConverter&lt;IFoo, Foo&gt;();
/// var options = new JsonSerializerOptions();
/// options.Converters.Add(converter);
///
/// var json = JsonSerializer.Serialize(objectWithAnIFoo, options);
/// IObjectWithAnIFoo objectFromJson = JsonSerializer.Deserialize&lt;ObjectWithAnIFoo&gt;(json, options);</code></pre>
/// </example>
/// <typeparam name="TInterface">The interface type being converted.</typeparam>
/// <typeparam name="TObject">The object type being converted.</typeparam>
public class ObjectInterfaceJsonConverter<TInterface, TObject>
: JsonConverter<TInterface> where TObject : TInterface
{
public override TInterface Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
=> (TInterface)JsonSerializer.Deserialize(ref reader, typeof(TObject), options);
public override void Write(Utf8JsonWriter writer, TInterface value, JsonSerializerOptions options)
=> JsonSerializer.Serialize(writer, (TObject)value, typeof(TObject), options);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment