Created
March 2, 2021 04:17
-
-
Save algonzalez/cc9081a8ab99409046f17296ae057c78 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// <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<IFoo, Foo>(); | |
/// var options = new JsonSerializerOptions(); | |
/// options.Converters.Add(converter); | |
/// | |
/// var json = JsonSerializer.Serialize(objectWithAnIFoo, options); | |
/// IObjectWithAnIFoo objectFromJson = JsonSerializer.Deserialize<ObjectWithAnIFoo>(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