I'm trying to serialize an object that has a Type
property into JSON. By default this isn't allowed due to security concerns, so I'm wondering if it's possible with an explicit converter (or if it's not even a good idea).
Here is the converter I wrote based on what I got from this MSDN tutorial. It uses Type.GetType
to try to convert any type in two of my own assemblies (neither of which contains this class).
internal class TypeConverter : JsonConverter<Type>
{
public override Type Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
string s = reader.GetString();
return Type.GetType($"{s}, {nameof(MyAssembly1)}", throwOnError: false)
?? Type.GetType($"{s}, {nameof(MyAssembly2)}");
}
public override void Write(Utf8JsonWriter writer, Type value, JsonSerializerOptions options)
{
writer.WriteStringValue(value.ToString());
}
}
My test code executes and produces the appropriate JSON, but on deserialization the Type
property is null
.
Is what I am trying to do possible/recommended? If so, how can I fix this issue?