0

I have the JSON Data from the below URL: http://api.openweathermap.org/data/2.5/forecast?q=Chennai&appid=2e0bfcd75d67a0452c6890c445c51030&units=metric

My ForecastController:

public class ForecastController : Controller
{

    // GET: Forecast
    public async Task<ActionResult> FiveDayForecast(string txtCity)
    {
        HttpResponseMessage httpResponse = null;
        using (var Client = new HttpClient())
        {
            try
            {
             Client.BaseAddress = new Uri("http://api.openweathermap.org");
             httpResponse = await Client.GetAsync($"/data/2.5/forecast?
             q=Chennai&appid=2e0bfcd75d67a0452c6890c445c51030&units=metric");



                httpResponse.EnsureSuccessStatusCode();
                var stringResult = await httpResponse.Content.ReadAsStringAsync();
                ForecastModel rawWeather = new ForecastModel();
                rawWeather = JsonConvert.DeserializeObject<ForecastModel>(stringResult);
                return View(rawWeather);
            }
            catch (HttpRequestException httpRequestException)
            {
                return View($"Error getting weather from OpenWeather: {httpRequestException.Message}");
            }

        }       
      }
     }

ForecastModel:

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace WeatherForecast.Models
{
[JsonObject]
public class ForecastModel 
{
    public string cod { get; set; }
    public double message { get; set; }
    public int cnt { get; set; }
    public List<List> list { get; set; }
    public City city { 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 Sys
{
    public string pod { get; set; }
}

public class Rain
{
    public double __invalid_name__3h { get; set; }
}

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

public class Coord
{
    public double lat { get; set; }
    public double lon { get; set; }
}

public class City
{
    public int id { get; set; }
    public string name { get; set; }
    public Coord coord { get; set; }
    public string country { get; set; }
}

}

View:

@model IEnumerable<WeatherForecast.Models.ForecastModel>

@{
ViewBag.Title = "FiveDayForecast";
}

 <h2>5 day weather forecast</h2>

<div class="weather-forecast-list">
<h3 class="weather-forecast-header">5 day weather forecast</h3>
</div>

@foreach (var item in @Model)
{
<table class="weather-forecast-list-table">
    <tbody>
        <tr class="weather-forecast-list-items-today">
            <td class="weather-forecast-list-item">
                <div class="weather-forecast-list-today-label">Today</div>
            </td>
            @*<img src="@Url.Content()" alt="Image" />*@
            <td class="weather-forecast-list-item">
                <span class="weather-forecast-list-day"></span>
                <span class="weather-forecast-list-night"></span>
            </td>
        </tr>
        <tr class="weather-forecast-list-items">
            <td class="weather-forecast-list-item"></td>
            <td class="weather-forecast-list-item">
                <span></span>
                <span></span>
            </td>
        </tr>
    </tbody>
</table>

}

I get the following error:

The model item passed into the dictionary is of type 'WeatherForecast.Models.ForecastModel', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable`1[WeatherForecast.Models.ForecastModel]'

I have tried many options like casting it a list and all other possibilities that i found.No luck.

 List<ForecastModel> rawWeather = new List<ForecastModel>();
 rawWeather = JsonConvert.DeserializeObject<List<ForecastModel>>
 (stringResult);

Then i get the below error: Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[WeatherForecast.Models.ForecastModel]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly. To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object. Path 'cod', line 1, position 7.

Somebody please show some light. Thanks a lot.

Nithya
  • 148
  • 2
  • 6
  • Because your view (which you did not show us) has `@model IEnumerable<...ForecastModel>` but you only pass a single `ForecastModel` –  Sep 22 '17 at 09:44
  • Hi Stephen,I have added my view now,and i have referred to the previous question and it does not apply to my case.I have been hitting my brain hard for the last 2 days. – Nithya Sep 22 '17 at 09:47
  • Of course it applies! You passing a **SINGLE** instance of `ForecastModel` to a view which expect a collection –  Sep 22 '17 at 09:48
  • I changed it to be as below:List rawWeather = new List(); rawWeather = JsonConvert.DeserializeObject>(stringResult); – Nithya Sep 22 '17 at 09:51
  • FGS - your generating a single `ForecastModel` - your model needs to be `@model WeatherForecast.Models.ForecastModel` (not `IEnumerable<..>`) –  Sep 22 '17 at 09:58
  • Error from my view: Compiler Error Message: CS1579: foreach statement cannot operate on variables of type 'WeatherForecast.Models.ForecastModel' because 'WeatherForecast.Models.ForecastModel' does not contain a public definition for 'GetEnumerator' – Nithya Sep 22 '17 at 10:06
  • Well of course not - its a single object, not a collection of objects - you cannot loop through a single object (although you could loop through the `list` property of your model since that is a collection) –  Sep 22 '17 at 10:08
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/155068/discussion-between-nithya-and-stephen-muecke). – Nithya Sep 22 '17 at 10:08

0 Answers0