0

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?

AndrewSilver
  • 976
  • 2
  • 14
  • 25
  • Why not use a factory instead? you'll serialize just a key, that it is used to generate the related type. I imagine you won't have to de/serialize every kind of object. – Mario Vernari Dec 03 '21 at 15:17
  • Your `JsonConverter` looks OK. Most likely you have issues with getting a type using `Type.GetType($"{s}, {nameof(MyAssembly1)}"`. Check this part – AndrewSilver Dec 04 '21 at 04:12

0 Answers0