简体   繁体   English

序列化异常:意外字符'<'

[英]Serialization Exception: unexpected character '<'

I have this simple method which suppose to get weather data, when I call it this error occur: 我有这个简单的方法,假设得到天气数据,当我调用它时会发生这样的错误:

System.Runtime.Serialization.SerializationException was unhandled by user code HResult=-2146233076 Message=There was an error deserializing the object of type UWpWeather.RootObject. System.Runtime.Serialization.SerializationException未由用户代码处理HResult = -2146233076 Message =反序列化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;
}

The API does not honour any of the HTTP content or Accept headers you pass through on the request, but rather it sets the content-type of the response based on the query string parameter. 该API 接受任何HTTP内容或接受你经过的请求头,而是将内容类型基于查询字符串参数的响应。

Your initial URL: 您的初始网址:

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= XML&单位=度量&CNT = 3&的appid = MY AIP-KEY”

What it should be: 应该是什么:

http://api.openweathermap.org/data/2.5/forecast/daily?q=leeds&type=accurate&mode= json &units=metric&cnt=3&appid= MY AIP-KEY" http://api.openweathermap.org/data/2.5/forecast/daily?q=leeds&type=accurate&mode= JSON&单位=度量&CNT = 3&的appid = MY AIP-KEY”

That should allow you to deserialize it into your RootObject correctly. 这应该允许您正确地将其反序列化到RootObject

Caveat: I don't have your root object implementation, so I could only verify up until getting a JSON-formatted response back. 警告:我没有你的根对象实现,所以我只能在获得JSON格式的响应之前进行验证。

I found the answer, my first mistake was using Xml instead of Json when calling my data. 我找到了答案,我的第一个错误是在调用我的数据时使用Xml而不是Json。 second, when I used this website ( json2csharp ) to convert Json to series of classes that represent my Json it created it fine except one which created as a list public List<List> list { get; set; } 第二,当我使用这个网站( json2csharp )将Json转换为代表我的Json的一系列类时,它创建它很好,除了一个创建为列表public List<List> list { get; set; } public List<List> list { get; set; } public List<List> list { get; set; } I simply removed that one and my code now is working just fine. public List<List> list { get; set; }我只是删除了一个和我的代码现在工作得很好。 thanks all for your support. 谢谢大家的支持。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM