Tibix
Tibix

Reputation: 17

C# JSON I cannot deserialize doubles. I get "Not a valid integer error"

So I was trying to deserialize weather data but it doesn't work. It just gives me an error:

"21.43 Not a valid integer"

Here's my code:

WebRequest request = HttpWebRequest.Create("https://api.openweathermap.org/data/2.5/weather?q=Budapest&APPID=CENSURED");
WebResponse response = request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());

string Weather_JSON = reader.ReadToEnd();
MessageBox.Show(Weather_JSON);
RootObject myWeather = Newtonsoft.Json.JsonConvert.DeserializeObject<RootObject>(Weather_JSON)
double temp = myWeather.main.temp;
label2.Text = label2.Text + temp;

I've also tried using:

RootObject myWeather = Newtonsoft.Json.JsonConvert.DeserializeObject<RootObject>(Weather_JSON, new JsonSerializerSettings(){ Culture = System.Globalization.CultureInfo.InvariantCulture });

Upvotes: 0

Views: 3494

Answers (3)

Shakir Ahmed
Shakir Ahmed

Reputation: 547

1 First of all, you have to deserialize your JSON object into an appropriate C# object with the help of Quick Type

You just paste ur json object into the left side textbox. It will automatically convert ur JSON data into a C# object. hahahaha. Easy, right?

Suppose, this my url: https://samples.openweathermap.org/data/2.5/weather?q=London,uk&appid=b6907d289e10d714a6e88b30761fae22

this is your JSON data after deserialize:

using System;
using System.Collections.Generic;

using System.Globalization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;

public partial class Welcome
{
    [JsonProperty("coord")]
    public Coord Coord { get; set; }

    [JsonProperty("weather")]
    public List<Weather> Weather { get; set; }

    [JsonProperty("base")]
    public string Base { get; set; }

    [JsonProperty("main")]
    public Main Main { get; set; }

    [JsonProperty("visibility")]
    public long Visibility { get; set; }

    [JsonProperty("wind")]
    public Wind Wind { get; set; }

    [JsonProperty("clouds")]
    public Clouds Clouds { get; set; }

    [JsonProperty("dt")]
    public long Dt { get; set; }

    [JsonProperty("sys")]
    public Sys Sys { get; set; }

    [JsonProperty("id")]
    public long Id { get; set; }

    [JsonProperty("name")]
    public string Name { get; set; }

    [JsonProperty("cod")]
    public long Cod { get; set; }
}

public partial class Clouds
{
    [JsonProperty("all")]
    public long All { get; set; }
}

public partial class Coord
{
    [JsonProperty("lon")]
    public double Lon { get; set; }

    [JsonProperty("lat")]
    public double Lat { get; set; }
}

public partial class Main
{
    [JsonProperty("temp")]
    public double Temp { get; set; }

    [JsonProperty("pressure")]
    public long Pressure { get; set; }

    [JsonProperty("humidity")]
    public long Humidity { get; set; }

    [JsonProperty("temp_min")]
    public double TempMin { get; set; }

    [JsonProperty("temp_max")]
    public double TempMax { get; set; }
}

public partial class Sys
{
    [JsonProperty("type")]
    public long Type { get; set; }

    [JsonProperty("id")]
    public long Id { get; set; }

    [JsonProperty("message")]
    public double Message { get; set; }

    [JsonProperty("country")]
    public string Country { get; set; }

    [JsonProperty("sunrise")]
    public long Sunrise { get; set; }

    [JsonProperty("sunset")]
    public long Sunset { get; set; }
}

public partial class Weather
{
    [JsonProperty("id")]
    public long Id { get; set; }

    [JsonProperty("main")]
    public string Main { get; set; }

    [JsonProperty("description")]
    public string Description { get; set; }

    [JsonProperty("icon")]
    public string Icon { get; set; }
}

public partial class Wind
{
    [JsonProperty("speed")]
    public double Speed { get; set; }

    [JsonProperty("deg")]
    public long Deg { get; set; }
}

public partial class Welcome
{
    public static Welcome FromJson(string json) => JsonConvert.DeserializeObject<Welcome>(json, QuickType.Converter.Settings);
}

public static class Serialize
{
    public static string ToJson(this Welcome self) => JsonConvert.SerializeObject(self, QuickType.Converter.Settings);
}

internal static class Converter
{
    public static readonly JsonSerializerSettings Settings = new JsonSerializerSettings
    {
        MetadataPropertyHandling = MetadataPropertyHandling.Ignore,
        DateParseHandling = DateParseHandling.None,
        Converters =
        {
            new IsoDateTimeConverter { DateTimeStyles = DateTimeStyles.AssumeUniversal }
        },
    };
}



 public static async void RefreshDataAsync()
        {           
                //check for internet connection
                if (CheckForInternetConnection())
                {
                    string uri = "https://samples.openweathermap.org/data/2.5/weather?q=London,uk&appid=b6907d289e10d714a6e88b30761fae22";

                    try
                    {
                        HttpResponseMessage response = await App.client.GetAsync(uri);
                        try
                        {
                            response.EnsureSuccessStatusCode();
                            var stringContent = await response.Content.ReadAsStringAsync();
                            welcome = Welcome.FromJson(stringContent);

                            FetchDataHelper.FetchUserData(welcome.User, UserModel_Data);
                            User_Data = welcome.User;
                        }
                        catch
                        {
                            return;
                        }
                    }
                    catch
                    {
                        //cannot communicate with server. It may have many reasons.
                        return;
                    }
                }
        }

After getting "welcome". You can show ur data!

Note: Don't copy and paste my code. Its just prototype. You have to paste your code in your project.

Upvotes: 0

CyrilDex
CyrilDex

Reputation: 177

If you do not wish to change the dataType of Root.main.temp, then convert it to a double.

For example: double temp = Double.TryParse(myweather.main.temp)

Note this method potentially throws an exception which you should handle.

Upvotes: 0

Mert Demir
Mert Demir

Reputation: 51

What is your RootObject’s properties? Weather value shouldn’t be integer make it double, float or decimal

Upvotes: 1

Related Questions