Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serialization Exception: unexpected character '<'

Tags:

c#

api

weather

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. 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;
}
like image 238
khalefa Avatar asked Nov 07 '22 22:11

khalefa


1 Answers

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.

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"

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"

That should allow you to deserialize it into your RootObject correctly.

Caveat: I don't have your root object implementation, so I could only verify up until getting a JSON-formatted response back.

like image 133
Yannick Meeus Avatar answered Nov 15 '22 05:11

Yannick Meeus