Get JSON file from an API

Asked

Viewed 34 times

0

I’m beginning to understand about API but I’m having a great difficulty because I’m trying to consume a JSON from an API according to the code below:

        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url + api);
        request.ContentType = "application/json";
        request.Method = "GET";
        request.Timeout = 30000;
        request.ReadWriteTimeout = 30000;

        var httpResponse = (HttpWebResponse)request.GetResponse();
        using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
        {
            var jsonReturn = streamReader.ReadToEnd();

            dynamic dobj = JsonConvert.DeserializeObject<dynamic>(jsonReturn);
        }

But this way it is giving error (Newtonsoft.Json.Jsonreaderexception: 'Unexpected Character encountered while Parsing value: <. Path '', line 0, position 0.')

Debugging the code I noticed that the var jsonReturn is in bringing a file HTML and in the dynamic dobj is giving the error quoted above.

1 answer

1


what is happening is that the application is returning an error in html and not a json, so Newtonsoft cannot deserialize since the return is a string and not a json.

try validating the status code to ensure that it will only deserialize if the status is successful.

  • Thank you Cristiano, helped me a lot your answer.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.