I want to obtain the values of properties of a complex model (IList(Object) in object)). I find the the main properties of the parent object and also the type of the childobject which I need. But I cannot extract its values.
I think the issue is due to the obect parameter in the GetValue method. It needs to be the "TheMovieDatabaseModelDetails" object. I've tried a lot of various options here, but get the error: "object does not match target type".
Model:
public class TheMovieDatabaseModel
{
public int page { get; set; }
public int total_results { get; set; }
public int total_pages { get; set; }
public IList<TheMovieDatabaseModelDetails> results { get; set; }
}
Code:
private async Task GetMovieDetailsForTheMovieDatabase<T>(T movieModel)
{
PropertyInfo[] propertyInfo = movieModel.GetType().GetProperties();
foreach (PropertyInfo property in propertyInfo)
{
if (property.Name.Equals("results"))
{
var movieDetails = property.GetType().GetProperties();
foreach (var detail in movieDetails)
{
detail.GetValue(movieDetails, null); // here I need to fill in the right "object".
}
}
// etc..
}
}
research (amongst others): Get Values From Complex Class Using Reflection
I've found the answer in:
I needed to created an IEnumerable first, as the parent model creates an IList of the ChildModel (movies, which have the moviedetails):
if (property.Name.Equals("results"))
{
object movieObject = property.GetValue(movieModel);
IEnumerable movieObjectList = movieObject as IEnumerable;
if (movieObjectList != null)
{
foreach (object movie in movieObjectList)
{
PropertyInfo[] movieDetails = movie.GetType().GetProperties();
foreach (PropertyInfo detail in movieDetails)
{
detail.GetValue(movie, null);
}
}
}
}