Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

C#

C# ASP.NET MVC - Dealing with an API that returns an XML

Hi,

So currently my basic web application retrieves data from the openweathermap api, for 1 day weather. The API used here returns just a single Json object.

http://api.openweathermap.org/data/2.5/weather?q=London&units=metric

However when I want to modify my application in order to use the 5 day forecast, the api returns the data as XML:

http://api.openweathermap.org/data/2.5/forecast?q=London,us&mode=xml

I'm not sure how to process this information.

Currently I have a class with a method that calls the API:

string url = "http://api.openweathermap.org/data/2.5/weather?q=London&units=metric&APPID=";

var webclient = new WebClient();
var urlcontent = client.DownloadString(url);
var jsserializer = new JavaScriptSerializer();
var newjsonContent = serializer.Deserialize<Object>(content);
return newjsonContent;

Any ideas please?

Thanks

1 Answer

Michael Hulet
Michael Hulet
47,913 Points

If you'll notice, in the 2nd URL you posted, you specified that you want the return value to be in XML. The documentation of that API specifies that the mode variable you set has 2 possible values: xml and JSON. If you omit that variable altogether, the API will return JSON by default. Thus, you have 2 options: You can either remove &mode=xml from the end of your URL, or you can change xml to JSON in that URL. Both methods will ask the API to return JSON instead of XML