gpt4 book ai didi

c# - JSON 不反序列化某些值

转载 作者:太空宇宙 更新时间:2023-11-03 22:40:45 25 4
gpt4 key购买 nike

我正在使用返回以下 JSON 的 API

{"coord":{"lon":-1.38,"lat":54.91},"weather":[{"id":801,"main":"Clouds","description":"few clouds","icon":"02d"}],"base":"stations","main":{"temp":285.83,"pressure":1013,"humidity":76,"temp_min":285.15,"temp_max":286.15},"visibility":10000,"wind":{"speed":5.1,"deg":240},"clouds":{"all":20},"dt":1536913200,"sys":{"type":1,"id":5104,"message":0.0049,"country":"GB","sunrise":1536903391,"sunset":1536949457},"id":2636531,"name":"Sunderland","cod":200}

我调用 API 并将 JSON 作为字符串 (strJson) 返回,我使用以下代码从 strJson 反序列化 JSON 并返回值。

JsonResponse res = JsonConvert.DeserializeObject<JsonResponse>(strJson);

我可以通过在我的 JsonResponse 类中使用以下内容来返回驻留在“天气”中的项目(我目前只返回“主要”,它成功运行;

class JsonResponse
{

public object coord { get; set; }
public IList<Weather> weather { get; set; }
}

 class Weather
{
public string main { get; set; }
}

我已经尝试了各种方法来返回驻留在“coord”和“sys”中的数据,但我一直收到错误“无法将 JSON 数组(例如 [1,2,3])反序列化为类型'',因为类型需要 JSON 对象(例如 {“name”:“value”})才能正确反序列化。

我可以使用

返回一个“对象”
public object coord {get; set;}

但是这并不有效,因为我仍然无法快速提取变量 lon 和 Lat 以及它们的值。

任何帮助将不胜感激,因为我之前问过类似的问题,但是我找到的答案阻止我从“天气”中提取值,所以我很困惑。

最佳答案

这是怎么回事?

class JsonResponse
{
public CoordObject coord {get;set;}
}

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

然后您应该能够访问 res.coord.lonres.coord.lat

通过快速搜索“json detect class”,我找到了这个有用的网站:json2csharp它为您的 JSON 生成了以下类:

public class Coord
{
public double lon { get; set; }
public double lat { 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 Main
{
public double temp { get; set; }
public int pressure { get; set; }
public int humidity { get; set; }
public double temp_min { get; set; }
public double temp_max { get; set; }
}

public class Wind
{
public double speed { get; set; }
public int deg { get; set; }
}

public class Clouds
{
public int all { get; set; }
}

public class Sys
{
public int type { get; set; }
public int id { get; set; }
public double message { get; set; }
public string country { get; set; }
public int sunrise { get; set; }
public int sunset { get; set; }
}

public class RootObject
{
public Coord coord { get; set; }
public List<Weather> weather { get; set; }
public string @base { get; set; }
public Main main { get; set; }
public int visibility { get; set; }
public Wind wind { get; set; }
public Clouds clouds { get; set; }
public int dt { get; set; }
public Sys sys { get; set; }
public int id { get; set; }
public string name { get; set; }
public int cod { get; set; }
}

关于c# - JSON 不反序列化某些值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52329505/

25 4 0
文章推荐: javascript - document.getElementById 在 asp.net 中的
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com