Created
September 14, 2021 18:31
-
-
Save roy-t/53684c198c2ee2a5928e1deead1f4051 to your computer and use it in GitHub Desktop.
Polymorphic serialization/deserialization using System.Text.Json
This file contains hidden or 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
using System; | |
using System.Collections.Generic; | |
using System.Text.Json; | |
using System.Text.Json.Serialization; | |
namespace Poly | |
{ | |
public abstract class BaseClass | |
{ | |
public string Hello { get; } = "Hello"; | |
} | |
public class WorldClass : BaseClass | |
{ | |
public string World { get; } = "World"; | |
} | |
public class GoodbyeClass : BaseClass | |
{ | |
public string Bye { get; } = "Bye"; | |
} | |
public sealed class PolyFake | |
{ | |
public PolyFake(string fullType, object target) | |
{ | |
this.FullType = fullType; | |
this.Target = target; | |
} | |
public string FullType { get; } | |
public object Target { get; } | |
} | |
public sealed class BaseClassConverter<T> : JsonConverter<T> | |
{ | |
public override bool CanConvert(Type typeToConvert) | |
{ | |
return typeof(T) == typeToConvert; | |
} | |
public override T? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) | |
{ | |
// Reader needs to deseralize the polyclass, get the type from FullType, then deserialize the inner section as that specific type and return that, its as if the wrapper class was never there | |
throw new NotImplementedException(); | |
} | |
public override void Write(Utf8JsonWriter writer, T value, JsonSerializerOptions options) | |
{ | |
var polyFake = new PolyFake(value.GetType().FullName, value); | |
//writer.WriteStartObject("polyFake"); | |
JsonSerializer.Serialize(writer, polyFake, options); | |
//writer.WriteEndObject(); | |
} | |
} | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
var list = new List<BaseClass>() | |
{ | |
new WorldClass(), | |
new GoodbyeClass(), | |
}; | |
var options = new JsonSerializerOptions(); | |
options.Converters.Add(new BaseClassConverter<BaseClass>()); | |
var text = JsonSerializer.Serialize(list, options); | |
Console.WriteLine("Plain:\n" + text); | |
Console.ReadLine(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment