lundi 14 mai 2018

Get object value inside a nested list using reflection

I have these 2 objects:

public class OpenWeather
{
    //Some properties

    public List<Weather> weather { get; set; }
    public Temp temperaures {get; set;}
    //some other properties
}

public class Weather
{
    public int id { get; set; }
    public string main { get; set; }
    public string description { get; set; }
    public string icon { get; set; }
}
    public class Temps 
    {
        public double temp { get; set; }
        public double temp_min { get; set; }
        public double temp_max { get; set; }
    }

And this method to access nested objects using reflection:

    public object GetPropertyValue(object obj, string propertyName)
    {
        var objType = obj.GetType();
        var prop = objType.GetProperty(propertyName);

        return prop.GetValue(obj, null);
    }

So for example, if I have to get the "temp" value of the "Temps" object nested inside the "OpenWeather" object I do this:

string temp = "Temperature: " + GetPropertyValue(GetPropertyValue(previsione, "temperatures"), "temp");

But how do I get the First object properties from the nested list of "Weather" objects inside the "OpenWeather" object?





Aucun commentaire:

Enregistrer un commentaire