我有一个简单的方法来获取天气数据,当我调用它时发生了这个错误:
System.Runtime.Serialization.SerializationException was unhandled by user code HResult=-2146233076 Message=There was an error deserializing the object of type UWpWeather.RootObject. Encountered unexpected character '<'.
public async static Task <RootObject> GetWeather(double lat, double lng) {
var http = new HttpClient();
var response = await http.GetAsync("http://api.openweathermap.org/data/2.5/forecast/daily?q=leeds&type=accurate&mode=xml&units=metric&cnt=3&appid= MY AIP-KEY");
string result = await response.Content.ReadAsStringAsync();
var serializer = new DataContractJsonSerializer(typeof (RootObject));
var ms = new MemoryStream(Encoding.UTF8.GetBytes(result));
var data = (RootObject) serializer.ReadObject(ms);
return data;
}
最佳答案
API 不接受您在请求中传递的任何 HTTP 内容或接受 header ,而是根据查询字符串参数设置响应的内容类型。
您的初始网址:
http://api.openweathermap.org/data/2.5/forecast/daily?q=leeds&type=accurate&mode=xml&units=metric&cnt=3&appid= MY AIP-KEY"
它应该是什么:
http://api.openweathermap.org/data/2.5/forecast/daily?q=leeds&type=accurate&mode=json&units=metric&cnt=3&appid= MY AIP-KEY"
这应该允许您将其反序列化为您的 RootObject
正确。
警告:我没有您的根对象实现,所以我只能在收到 JSON 格式的响应之前进行验证。
关于c# - 序列化异常 : unexpected character '<' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43698529/