我正在尝试学习如何集成NOAA API( https://www.ncdc.noaa.gov/cdo-web/webservices/v2#gettingStarted)
使用类似于此处概述的方法:https://docs.microsoft.com/en-us/dotnet/csharp/tutorials/console-webapiclient
反序列化与特定位置相关的天气数据
我有一个Result.cs对象
public class Result
{
public DateTime Date { get; set; }
public string DataType { get; set; }
public string Station { get; set; }
public string Attributes { get; set; }
public int Value { get; set; }
}
我尝试序列化并写入控制台进行测试:
private static async Task ProcessRespositories()
{
var serializer = new DataContractJsonSerializer(typeof(List<Result>));
//token set from https://www.ncdc.noaa.gov/cdo-web/token
string token = "myToken";
var client = new HttpClient();
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Add("token", token);
//url taken from https://www.ncdc.noaa.gov/cdo-web/webservices/v2#data for daily summaries
string url = "https://www.ncdc.noaa.gov/cdo-web/api/v2/data?datasetid=GHCND&locationid=ZIP:28801&startdate=2010-05-01&enddate=2010-05-01"
//this is null
var streamTask = client.GetStreamAsync(url);
var repositories = serializer.ReadObject(await streamTask) as List<Result>;
foreach (var repo in repositories)
Console.WriteLine(repo.Value);
}
我从该网址流中获得的结果似乎是空的。我只是在学习但不确定我的错误。
答案 0 :(得分:1)
您从该响应中获得的有效负载如下所示:
{ “元数据”:{ “结果集合”:{ “偏移量”:1, “计数”:8, “限制”:25}}, “结果”:[{ “日期”:“2010-05-01T00 :00:00" , “数据类型”: “PRCP”, “站”: “GHCND:US1NCBC0005”, “属性”:” ,, N, “” 值 “:0},{” 日期 “:” 2010- 05-01T00:00:00" , “数据类型”: “SNOW”, “站”: “GHCND:US1NCBC0005”, “属性”: “,, N, ”“ 值”:0}]}
您为DataContractSerializer提供的类型需要与该有效负载匹配。你错过了一个顶级容器。字段的名称也区分大小写。我使用DataMember属性来调整正确的外壳。最后但并非最不重要的是,默认情况下不支持日期时间格式。现在我将其更改为字符串类型。您可能想看看https://stackoverflow.com/a/9347678/578411是否适合您或切换到Json.NET
以下是Model类
public class Noaa
{
public MetaData metadata {get;set;}
public List<Result> results;
}
public class MetaData
{
public ResultSet resultset {get;set;}
}
public class ResultSet
{
public int offset{get;set;}
public int count{get;set;}
public int limit{get;set;}
}
[DataContract]
public class Result
{
[DataMember(Name="date")]
public string Date { get; set; } // now a string!
[DataMember(Name="datatype")]
public string DataType { get; set; }
[DataMember(Name="station")]
public string Station { get; set; }
[DataMember(Name="attributes")]
public string Attributes { get; set; }
[DataMember(Name="value")]
public int Value { get; set; }
}
您的序列化程序需要更改为使用容器类型:
var serializer = new DataContractJsonSerializer(typeof(Noaa));
// other code the same
// call the serializer
var repositories = (Noaa) serializer.ReadObject(await streamTask);
// respositories is now a Noaa type,
// its member results holds your list.
foreach (var repo in repositories.results)
Console.WriteLine(repo.Value);
如果要检查有效负载而不是将其交给序列化程序,可以像这样使用StreamReader:
var sw= new StreamReader(await streamTask);
Console.WriteLine(sw.ReadToEnd());
这样的网络代理商