Tom Mein Tom Mein - 10 months ago 84
JSON Question

Get OpenWeatherMap JSON data to view

I am trying to use OpenWeatherMap to provide a weather feed to an MVC built website.
Model as follows:

{
public class OpenWeatherMap
{
public List<Data> list;
}

public class Data
{
public Main main { get; set; }
public List<Weather> weather { get; set; }
public Clouds clouds { get; set; }
public Wind wind { get; set; }
public Rain rain { get; set; }
public string dt_txt { get; set; }
}

public class Main
{
public double temp { get; set; }
public double temp_min { get; set; }
public double temp_max { get; set; }
public double pressure { get; set; }
public double sea_level { get; set; }
public double grnd_level { get; set; }
public int humidity { get; set; }
public double temp_kf { get; set; }
}

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 Clouds
{
public int all { get; set; }
}

public class Wind
{
public double speed { get; set; }
public double deg { get; set; }
}
public class Rain
{
public double rain { get; set; }
}

public class Sys
{
public string pod { get; set; }

}
}


Controller as follows:

public OpenWeatherMap GetLocalWeather()
{

string apiUrl = BaseURL + "id=" + CityID + "&appid=" + AppID + "&units=metric";

string result = RequestHandler.Process(apiUrl);

OpenWeatherMap lWeather = new JavaScriptSerializer().Deserialize<OpenWeatherMap>(result);


return lWeather;
}

public ActionResult Index()
{
OpenWeatherMap localWeather = GetLocalWeather();

return View();
}


I have two questions:


  1. What is the best method to proceed to pass the data to the View and have noticed that now and again the JSON data will omit items e.g. the rainfall data today disappeared.

  2. What is the best method to cover such an event?


Answer Source

This will fix your issue.

public class Weather { 
    private double _rain; 
    public double Rain { 
        get { if     (_rain != null) return _rain; else return 0.0; } 
        set { _rain = value; } } 
} 
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download