C#JSON我无法反序列化双打。我得到“不是有效的整数错误”

问题描述 投票:0回答:3

所以我试图反序列化天气数据,但它不起作用。它只是给我一个错误:

“21.43不是有效整数”

这是我的代码:

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;

我也尝试过使用:

RootObject myWeather = Newtonsoft.Json.JsonConvert.DeserializeObject<RootObject>(Weather_JSON, new JsonSerializerSettings(){ Culture = System.Globalization.CultureInfo.InvariantCulture });
c# json api serialization culture
3个回答
1
投票

你的RootObject的属性是什么?天气值不应为整数,使其为double,float或decimal


0
投票

如果您不想更改dataTypeRoot.main.temp,请将其转换为double

例如:double temp = Double.TryParse(myweather.main.temp)

请注意,此方法可能会引发您应该处理的异常。


0
投票

1首先,您需要在Quick Type的帮助下将JSON对象反序列化为适当的C#对象

您只需将ur json对象粘贴到左侧文本框中即可。它会自动将您的JSON数据转换为C#对象。哈哈哈哈。容易,对吗?

假设,这是我的网址:https://samples.openweathermap.org/data/2.5/weather?q=London,uk&appid=b6907d289e10d714a6e88b30761fae22

这是反序列化后的JSON数据:

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;
                    }
                }
        }

得到“欢迎”后。你可以显示你的数据!

注意:请勿复制并粘贴我的代码。它只是原型。您必须将代码粘贴到项目中。

© www.soinside.com 2019 - 2024. All rights reserved.