How Newtonsoft.Json.JsonConvert.DeserializeObject and System.Text.Json.JsonSerializer.Deserialize can convert a variable using Type information?

Viewed 60

I have a variable of type ExtendedUserModel which after deserialization, becomes an object of type Dictionary<object,object>. (that Dictionary<object,object> is the result of deserialization using MessagePack)

At compile time I cannot cast Dictionary<object,object> to ExtendedUserModel for reasons that are related to how the codebase was implemented. But I do have access to the variable named type which is basically equal to typeof(ExtendedUserModel)

The workaround: The followings can successfully do the casting at runtime without the need for type to have IConvertible interface implemented in it:

var castedObject = Newtonsoft.Json.JsonConvert.DeserializeObject(JsonConvert.SerializeObject(variable), type);

or:

var castedObject = System.Text.Json.JsonSerializer.Deserialize(JsonSerializer.Serialize(variable), type);

How Can I achieve the same without resorting to this serialization and deserialization?

Note:

  • As I said, using Convert.ChangeType(variable, type); is not an option because we cannot enforce the implementation of IConvertible interface.
  • I tried this response too, but I got: System.InvalidOperationException: No coercion operator is defined between types 'System.Collections.Generic.Dictionary`2[Sys tem.Object,System.Object]' and 'CoreConsoleApp1.ExtendedUserModel'.
0 Answers
Related