在c#中写作,我在这里得到jsonreaderexceptions:
var container = JsonConvert.DeserializeObject<HistoryResponseContainer> (responseData);
总是像未终止的线或未识别的字符一样。
我知道我需要捕获并丢弃这些错误,但是如果我尝试在try/catch语句中定义"容器",那会破裂。这是整个方法。
foreach (String StationID in StationIDList) {
string url = @"http://api.wunderground.com/api/" + wundergroundkey + "/history_" + Date + "/q/pws:" + StationID + ".json";
Uri uri = new Uri (url);
WebRequest webRequest = WebRequest.Create (uri);
WebResponse response = webRequest.GetResponse ();
StreamReader streamReader = new StreamReader (response.GetResponseStream ());
String responseData = streamReader.ReadToEnd ();
var container = JsonConvert.DeserializeObject<HistoryResponseContainer> (responseData);
foreach (var observation in container.history.observations) {
CurrentData.Write (StationID + " ");
// This makes easier access to the date. not perfect, but better.
DateTime date = observation.date.Value;
DateTime utc = observation.utcdate.Value;
// whatever you want to do with each observation
if (date.Minute == 0 || date.Minute % 5 == 0) {
CurrentData.Write (date.Hour + ":" + date.Minute + " " + observation.wdird + " " + observation.wspdi);
}//end if
CurrentData.Write ("n");
} //End foreach observation
} //end foreach station
将您的第二个foreach循环放入"尝试"(因为您使用的"容器")。否则,如果提出异常,则不会定义它,而您仅"尝试/捕获"您的容器Intanciation:
foreach (String StationID in StationIDList)
{
string url = @"http://api.wunderground.com/api/" + wundergroundkey + "/history_" + Date + "/q/pws:" + StationID + ".json";
Uri uri = new Uri (url);
WebRequest webRequest = WebRequest.Create (uri);
WebResponse response = webRequest.GetResponse ();
StreamReader streamReader = new StreamReader (response.GetResponseStream ());
String responseData = streamReader.ReadToEnd ();
try
{
var container = JsonConvert.DeserializeObject<HistoryResponseContainer> (responseData);
foreach (var observation in container.history.observations)
{
CurrentData.Write (StationID + " ");
DateTime date = observation.date.Value;
DateTime utc = observation.utcdate.Value;
if (date.Minute == 0 || date.Minute % 5 == 0)
{
CurrentData.Write (date.Hour + ":" + date.Minute + " " + observation.wdird + " " + observation.wspdi);
}
CurrentData.Write ("n");
}
}
catch(JsonReaderException ex)
{
// ...
}
}
我知道我需要捕获并扔这些错误,
不,您需要捕获并处理这些错误。
,但是如果我尝试在尝试/捕获语句中定义"容器",那就呕吐。
您在这里是什么意思?您需要这个:
try
{
// your code that throws exception
}
catch(JsonReaderException ex)
{
// handle your exception
}