对不起,我是C#的新手。
如何通过该Wather API与数据合约反序列化
我应该使用什么,任何人都可以帮我吗?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Net;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Linq;
using System.Xml.Serialization;
using HtmlParserSharp.Core;
using Newtonsoft.Json;
using RestSharp;
using RestSharp.Deserializers;
class Program
{
static void Main(string[] args)
{
var clientWeather = new RestClient("http://api.worldweatheronline.com/premium/v1/weather.ashx");
var requestWeather = new RestRequest(Method.GET);
requestWeather.AddParameter("key", "c37f984779f14beb9bf01943201104", ParameterType.QueryString);
requestWeather.AddParameter("q", "Pristina", ParameterType.QueryString);
requestWeather.AddParameter("format", "xml", ParameterType.QueryString);
requestWeather.AddParameter("num_of_days", "5", ParameterType.QueryString);
IRestResponse responseWeather = clientWeather.Execute(requestWeather);
DataContractSerializer dcs = new DataContractSerializer(typeof(Request));
}
听起来像您几乎在那儿,只有几件事。
using System.IO;
using System.Net;
using System.Xml;
获取内容。您可以只使用HttpWebRequest中内置的C#请求信息。只需将您想要的内容构建为动态字符串即可。
var requestWeather = (HttpWebRequest)WebRequest.Create(@"http://api.worldweatheronline.com/premium/v1/weather.ashx?key=c37f984779f14beb9bf01943201104&q=Pristina&format=xml&num_of_days=5");
requestWeather.Method = "GET";
var content = string.Empty;
using (var response = (HttpWebResponse)requestWeather.GetResponse())
{
using (var stream = response.GetResponseStream())
{
using (var sr = new StreamReader(stream))
{
content = sr.ReadToEnd();
}
}
}
这里有点混乱。您返回的内容是XML。您可以在format参数中指定它,也可以使用JSON。
您可以使用此方法在XML中搜索所需的部分(更改所需标签的名称):
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(content);
XmlNodeList elemlist = xmlDoc.GetElementsByTagName("observation_time");
string result = elemlist[0].InnerXml;
结果=“上午09:41”
但是我需要使用反数据串反序列化器,而不使用流