c# - 反序列化 RESTSharp JSON 响应
问题描述
我正在开展一个从 NOAA 收集数据的项目。我无法弄清楚如何使响应可用。
这是 NOAA 的 API 响应对我的调用的样子:
{
"metadata": {
"resultset": {
"offset": 1,
"count": 38859,
"limit": 2
}
},
"results": [
{
"mindate": "1983-01-01",
"maxdate": "2019-12-24",
"name": "Abu Dhabi, AE",
"datacoverage": 1,
"id": "CITY:AE000001"
},
{
"mindate": "1944-03-01",
"maxdate": "2019-12-24",
"name": "Ajman, AE",
"datacoverage": 0.9991,
"id": "CITY:AE000002"
}
]
}
我使用 JSON2CSharp.com 将结果集转换为我需要的类。下面是相关代码:
public class NOAA
{
public class Resultset
{
public int offset { get; set; }
public int count { get; set; }
public int limit { get; set; }
}
public class Metadata
{
public Resultset resultset { get; set; }
}
public class Location
{
public string mindate { get; set; }
public string maxdate { get; set; }
public string name { get; set; }
public double datacoverage { get; set; }
public string id { get; set; }
}
public class RootObject
{
public Metadata metadata { get; set; }
public List<Location> results { get; set; }
}
public class Response
{
IList<Metadata> metadata;
IList<Location> results;
}
public void RestFactory(string Token, string Endpoint, Dictionary<string, string> Params)
{
// Initiate the REST request
var client = new RestClient("https://www.ncdc.noaa.gov/cdo-web/api/v2/" + Endpoint);
var request = new RestRequest(Method.GET);
// Add the token
request.AddHeader("token", Token);
// Add the parameters
foreach (KeyValuePair<string, string> entry in Params)
{
request.AddParameter(entry.Key, entry.Value);
}
// Execute the REST request
var response = client.Execute(request);
// Deserialize the response
Response noaa = new JsonDeserializer().Deserialize<Response>(response);
// Print to console
foreach (Location loc in noaa)
{
Console.WriteLine(loc.name);
}
}
}
在这一点上,我只是试图打印位置名称以达到我的下一个学习里程碑。我收到错误:
Severity Code Description Project File Line Suppression State
Error CS1579 foreach statement cannot operate on variables of type 'NOAA.Response' because 'NOAA.Response' does not contain a public instance definition for 'GetEnumerator'
除了错误之外,我认为我不太了解正确的方法,因为响应有多个“层”。指导?
解决方案
您的 foreach 循环试图调用对象本身的迭代器,而不是其中的列表。
试试这个
foreach (Location loc in noaa.results)
{
Console.WriteLine(loc.name);
}
推荐阅读
- sql - 如何在 SQL Server 中获取上一个季度的月份和年份
- c# - 从派生类型的EIMI调用基类型中的EIMI
- angular - ngOnInit 从未在我的组件之一中运行
- python-3.x - 在 Python 的同一行中打印“多个函数输出”[不仅仅是打印字符串]
- python - 有没有办法在 Matplotlib 中从未接触过的两个垂直函数之间进行遮蔽?
- xcode - Swift 5. 目标:使应用程序在不使用 segues 的情况下打开特定的 View Controller
- windows - 为 GET_WHEEL_DELTA_WPARAM 创建 wParam
- java - Java 如何计算数组中数字的平均值?
- javascript - 在溢出表的屏幕上始终显示水平滚动条
- react-native - CameraRoll.saveToCameraRoll 不是函数(Expo)