vendredi 18 février 2022

How to get the value of a property and assign it to another property using reflection C#

I get a Json response and deserialize it into one of the models. I do not know the data type in advance, but i can get its name from the response and deserialize it using reflection. Then I try to assign a response(response.data) to the CommonModel field, but I get an error "Object does not match target type"

void Method(string typeName, string json)
    {
        CommonModel commonModel = new();
        Type modelType = Type.GetType($"{typeName}");
        var modelInstance = Activator.CreateInstance(modelType); //create instance of model, for example Model1

        Type openType = typeof(ResponseModel<>);
        Type[] tArgs = { modelType };
        Type target = openType.MakeGenericType(tArgs); //create instance of ResponseModel<>, for example ResponseModel<Model1>

        var methods = typeof(JsonSerializer);
        var method = methods.GetMethods().FirstOrDefault(w => w.IsGenericMethod && w.Name == "Deserialize" && w.GetParameters().Any(x => x.ParameterType.Name == "String"));
        MethodInfo generic = method.MakeGenericMethod(target); //Create JsonSerializer.Deserialize<T>(json), for example Deserialize<ResponseModel<Model1>>
        var instance = Activator.CreateInstance(target);
        var model = generic.Invoke(instance, new object[] { json, null }); //invoke deserialize method

        var data = model.GetType().GetProperty("data").GetValue(modelType, null); // Exception "Object does not match target type"
        //How do I get the model.data property and assign it to commonModel.{propertyName}
    }

public class Response<T>
    {
       public string request_id { get; set; }
       public T data { get; set; }
    }

   Public class Model1
{
   public string Field1 { get; set; }
   public string Field2 { get; set; }
}

Public class Model2
    {
       public string Field3 { get; set; }
       public string Field4 { get; set; }
    }

Public class CommonModel
        {
           public Model1 Model1 { get; set; }
           public Model2 Model2 { get; set; }
        }

As a T i use Model 1 or Model2.





Aucun commentaire:

Enregistrer un commentaire