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

Issue

This Content is from Stack Overflow. Question asked by wiki

I have a variable of type ExtendedUserModel which after serialization, becomes an object of type Dictionary<object,object>. (this is just an example of many classes like this)

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 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’.



Solution

This question is not yet answered, be the first one who answer using the comment. Later the confirmed answer will be published as the solution.

This Question and Answer are collected from stackoverflow and tested by JTuto community, is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?