Search code examples
c#json-deserialization

how to map complex json data into model class


about project: I am using following free api to get weather data. I am able to create Model class and map basic values and its working ok.

Question: But how do I map more complex values like hourly_units, which had sub parameters like time & temperature_2m. same thing about hourly which also has arrays of time & temperature_2m. Do I have to create multi Model class? or can this be doing with List?

public class WeatherModel
{
    public long latitude { get; set; }
    public long longitude { get; set; }
    public long generationtime_ms { get; set; }
    public long utc_offset_seconds { get; set; }

    public string timezone { get; set; }
    public string timezone_abbreviation { get; set; }
    public string elevation { get; set; }
}

JSON return is in following format:

enter image description here


Solution

  • have you tried creating them as sub classes

    public class WeatherModel
    {
        public long latitude { get; set; }
        public long longitude { get; set; }
        public long generationtime_ms { get; set; }
        public long utc_offset_seconds { get; set; }
    
        public string timezone { get; set; }
        public string timezone_abbreviation { get; set; }
        public string elevation { get; set; }
        
        Public class Hourly_Units {
             public string time { get; set; }
             public string temperature_2m { get; set; } 
        }   
        Public class Hourly {
             public List<string> time { get; set; }
        }   
    }