Error: The value '-5.94' cannot be parsed as the type 'Int32'.'

-1

Issue when trying to run weather app. Trying to get 5 day forecast from openweathermap url http://samples.openweathermap.org/data/2.5/forecast?lat=7.0744&lon=79.8919&appid=a7cae8ecfab2535dec05a83525f5ac7a But everytime it trys to parse the json I get the error.

System.Runtime.Serialization.SerializationException HResult=0x80131500 Message=There was an error deserializing the object of type WeatherApp.RootObject1. The value '-3.23' cannot be parsed as the type 'Int32'. Source=System.Private.DataContractSerialization StackTrace: at System.Runtime.Serialization.XmlObjectSerializer.ReadObjectHandleExceptions(XmlReaderDelegator reader, Boolean verifyObjectName, DataContractResolver dataContractResolver) at System.Runtime.Serialization.Json.DataContractJsonSerializerImpl.ReadObject(XmlDictionaryReader reader) at System.Runtime.Serialization.Json.DataContractJsonSerializerImpl.ReadObject(Stream stream) at System.Runtime.Serialization.Json.DataContractJsonSerializer.ReadObject(Stream stream) at WeatherApp.ForecastWeatherMapProxy.d__0.MoveNext() in C:\Users\KMora\source\repos\WeatherApp\WeatherApp\ForecastWeatherMapProxy.cs:line 23 at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult() at WeatherApp.MainPage.d__6.MoveNext() in C:\Users\KMora\source\repos\WeatherApp\WeatherApp\MainPage.xaml.cs:line 67

Inner Exception 1:

XmlException: The value '-3.23' cannot be parsed as the type 'Int32'.

Inner Exception 2:

OverflowException: Value was either too large or too small for an Int32.

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Threading.Tasks;

namespace WeatherApp
{
    public class ForecastWeatherMapProxy
    {
        public async static Task<RootObject1> GetWeather1(double lat, double lon)
        {
            var http = new HttpClient();
            var url = String.Format("http://api.openweathermap.org/data/2.5/forecast?lat={0}&lon={1}&units=metric&appid=5bfe62f124a556092c27cad0f9752109", lat, lon);
            var response = await http.GetAsync(url);
            var result = await response.Content.ReadAsStringAsync();
            var serializer = new DataContractJsonSerializer(typeof(RootObject1));
            var ms = new MemoryStream(Encoding.UTF8.GetBytes(result));
            var data = (RootObject1)serializer.ReadObject(ms);
            return data;
        }
    }

    [DataContract]
    public class Main1
    {
        [DataMember]
        public double temp { get; set; }
        [DataMember]
        public double temp_min { get; set; }
        [DataMember]
        public double temp_max { get; set; }
        [DataMember]
        public double pressure { get; set; }
        [DataMember]
        public double sea_level { get; set; }
        [DataMember]
        public double grnd_level { get; set; }
        [DataMember]
        public int humidity { get; set; }
        [DataMember]
        public int temp_kf { get; set; }
    }
    [DataContract]
    public class Weather1
    {
        [DataMember]
        public int id { get; set; }
        [DataMember]
        public string main { get; set; }
        [DataMember]
        public string description { get; set; }
        [DataMember]
        public string icon { get; set; }
    }
    [DataContract]
    public class Clouds1
    {
        [DataMember]
        public int all { get; set; }
    }
    [DataContract]
    public class Wind1
    {
        [DataMember]
        public double speed { get; set; }
        [DataMember]
        public double deg { get; set; }
    }
    [DataContract]
    public class Rain1
       {

       }
    [DataContract]
    public class Sys1
    {
        [DataMember]
        public string pod { get; set; }
    }
    [DataContract]
    public class List1
    {
        [DataMember]
        public int dt { get; set; }
        [DataMember]
        public Main1 main { get; set; }
        [DataMember]
        public List<Weather1> weather { get; set; }
        [DataMember]
        public Clouds1 clouds { get; set; }
        [DataMember]
        public Wind1 wind { get; set; }
        [DataMember]
        public Rain1 rain { get; set; }
        [DataMember]
        public Sys1 sys { get; set; }
        [DataMember]
        public string dt_txt { get; set; }
    }
    [DataContract]
    public class Coord1
    {
        [DataMember]
        public double lat { get; set; }
        [DataMember]
        public double lon { get; set; }
    }
    [DataContract]
    public class City1
    {
        [DataMember]
        public int id { get; set; }
        [DataMember]
        public string name { get; set; }
        [DataMember]
        public Coord1 coord { get; set; }
        [DataMember]
        public string country { get; set; }
    }
    [DataContract]
    public class RootObject1
    {
        [DataMember]
        public string cod { get; set; }
        [DataMember]
        public double message { get; set; }
        [DataMember]
        public int cnt { get; set; }
        [DataMember]
        public List<List1> list { get; set; }
        [DataMember]
        public City1 city { get; set; }
    }
}

This is where I call it from xaml.cs

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Media.Imaging;
using Windows.UI.Xaml.Navigation;

// The Blank Page item template is documented at https://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409

namespace WeatherApp
{
    /// <summary>
    /// An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>
    public sealed partial class MainPage : Page
    {
        public MainPage()
        {
            this.InitializeComponent();
            collection = new ObservableCollection<List1>();
            this.DataContext = this;
        }
      
        private async void Page_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                var position = await LocationManger.GetPostion();

                RootObject myWeather = await OpenWeatherMapProxy.GetWeather(
                    position.Coordinate.Latitude,
                    position.Coordinate.Longitude);
                string icon = String.Format("ms-appx:///Assets/Weather/{0}.png", myWeather.weather[0].icon);
                ResultImage.Source = new BitmapImage(new Uri(icon, UriKind.Absolute));

                TempResultTextBlock.Text = "Temperature: " + ((int)myWeather.main.temp).ToString()+ "°C";
                DescrptionResultTextBlock.Text = "Condition: " + myWeather.weather[0].description;
                LocationResultTextBlock.Text = "Location: " + myWeather.name;

               
             

            }
            catch  
            {
                LocationResultTextBlock.Text = "Error to get Location. Please allow access to location services " ;

            }
            
        }
        public ObservableCollection<List1> collection { get; set; }
        private async void Button_Click(object sender, RoutedEventArgs e)
        {
            
                var position = await LocationManger.GetPostion();

                RootObject1 myWeatherForecast = await ForecastWeatherMapProxy.GetWeather1(position.Coordinate.Latitude,
                    position.Coordinate.Longitude);
       
                for (int i = 0; i < 5; i++)
                {
                    collection.Add(myWeatherForecast.list[i]);
                }

                ForecastGridView.ItemsSource = collection;
            
          
        }
    }
}

Any advice as to the issue would be greatly appreciated.

c#
uwp-xaml
openweathermap
asked on Stack Overflow Apr 11, 2018 by Kevin Moran • edited Apr 11, 2018 by Diego Rafael Souza

1 Answer

0

You need to have a look at the raw json that's coming back from the web call. You're trying to deserialise the response as a "RootObject1", and that has a "cnt" property which is defined as an Int32 (int).

answered on Stack Overflow Apr 11, 2018 by Black Light

User contributions licensed under CC BY-SA 3.0