Json in c#

Tagged:

Currently contains 4 posts

Avatar

June 14, 2016 16:46

issharp1

I know you say that we can receive the data in a json format, but I am unsure how to do this. I believe I changed the accept header to “application/json”, but when run, none of the data ever appears; the forecast object is null. Could you give a sample c# call that returns the data in a json format?

Avatar

June 15, 2016 10:56

Marco

Hi,

please try using the following function to request the api like this:
string output = GET;


        public static string GET(string url, string output_type)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Accept = output_type;

            try
            {
                WebResponse response = request.GetResponse();
                using (Stream responseStream = response.GetResponseStream())
                {
                    StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
                    return reader.ReadToEnd();
                }
            }
            catch (WebException ex)
            {
                WebResponse errorResponse = ex.Response;
                using (Stream responseStream = errorResponse.GetResponseStream())
                {
                    StreamReader reader = new StreamReader(responseStream, Encoding.GetEncoding("utf-8"));
                    String errorText = reader.ReadToEnd();
                }

                throw;
            }
        }

got the function from here:
http://stackoverflow.com/a/8270654/1467453

cheers,

Marco

Avatar

June 15, 2016 12:48

issharp1

Once I have the output string, how do I actually separate it into classes? I’ve defined all of the classes that the json string will contain, but I don’t know how to actually create an object of the type that will be produced.

Avatar

June 16, 2016 08:55

Marco

Hi,

This link that might be helpful for you:
http://blog.anthonybaker.me/2013/05/how-to-consume-json-rest-api-in-net.html

It provides a good example of what you want to accomplish.

cheers,

Marco

Reply to thread
  1. If you're human, leave this field empty.