gpt4 book ai didi

c# - Invalidcastexception JsonConvert.DeserializeObject

转载 作者:行者123 更新时间:2023-11-30 14:07:45 24 4
gpt4 key购买 nike

我收到一个无效的强制转换异常,表明指定的强制转换无效。在这条线上:

RootObject mountain = JsonConvert.DeserializeObject<RootObject>(json1);

来自documentation这应该没问题?我可以看到控制台输出正常吗?

Response: [{"Height_ft": 2999.0, "Height_m": 914.0, "ID": "c1", "Latitude": 57.588007, "Longitude": -5.5233564, "Name": "Beinn Dearg", "humidity": 0.81, "snowCover": 4.99, "temperature": 63.0}]

        Spinner spinner = (Spinner)sender;
string urlmountain = "http://removed.azurewebsites.net/api/Mountains?name=";
JsonValue json1 = FetchMountain(urlmountain+string.Format("{0}", spinner.GetItemAtPosition(e.Position)));
//below.................................
RootObject mountain = JsonConvert.DeserializeObject<RootObject>(json1); //this line
string toast = mountain.Name;
Toast.MakeText(this, toast, ToastLength.Long).Show();

private JsonValue FetchMountain(string urlmountain)
{
// Create an HTTP web request using the URL:
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(new Uri(urlmountain));
request.ContentType = "application/json";
request.Method = "GET";

// Send the request to the server and wait for the response:
using (WebResponse response = request.GetResponse())
{
// Get a stream representation of the HTTP web response:
using (Stream stream = response.GetResponseStream())
{
// Use this stream to build a JSON document object:
JsonValue jsonDoc1 = JsonObject.Load(stream);
Console.Out.WriteLine("Response: {0}", jsonDoc1.ToString());

// Return the JSON document:
return jsonDoc1;
}
}
}
public class RootObject
{
public string ID { get; set; }

public double? Latitude { get; set; }

public double? Longitude { get; set; }

public string Name { get; set; }

public double? Height_m { get; set; }

public double? Height_ft { get; set; }

public double? temperature { get; set; }

public double? humidity { get; set; }

public double? snowCover { get; set; }

public override string ToString()
{
return Name;
}
}

最佳答案

返回的 json 数据是一个对象数组,而不是单个对象,如左右括号 [] 所示。您需要反序列化为数组或列表:

var mountains = JsonConvert.DeserializeObject<List<RootObject>>(json);

要从反序列化的有效负载访问第一座山,请使用 .FirstOrDefault()

var mountain = mountains.FirstOrDefault();
if (mountain != null)
{
string toast = mountain.Name;
Toast.MakeText(this, toast, ToastLength.Long).Show();
}

关于c# - Invalidcastexception JsonConvert.DeserializeObject,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38878748/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com