Ignacio Hernandez Ignacio Hernandez - 6 months ago 84
JSON Question

C# how can I get Json data from google api and store it in a variable

I am trying to send an Http Get message to the Google location Api which is supposed to have Json data such as this

https://maps.googleapis.com/maps/api/geocode/json?address=Los%20Angeles,CA=AIzaSyDABt
as you noticed the response is in Json. I want to give a a Http Call to that URL and save the Json content in a variable or string. My code does not give out any errors but it is also not returning anything

public async System.Threading.Tasks.Task<ActionResult> GetRequest()
{
var client = new HttpClient();

HttpResponseMessage response = await client.GetAsync("https://maps.googleapis.com/maps/api/geocode/json?address=Los%20Angeles,CA=AIzaSyDABt");
string data = response.Content.ToString();
return data;
}


I want to send out a Get Request using HttpClient() or anything that will send out the URL request and then save that content into a string variable . Any suggestions would be appreciated, again my code gives no errors but it is not returning anything.

Answer

Use ReadAsStringAsync to get the json response...

            static void Main(string[] args)
            {
                HttpClient client = new HttpClient();

                Task.Run(async () =>
                {
                    HttpResponseMessage response = await client.GetAsync("https://maps.googleapis.com/maps/api/geocode/json?address=Los%20Angeles,CA=AIzaSyDABt");
                    string responseString = await response.Content.ReadAsStringAsync();
                    Console.WriteLine(responseString);
                });

                Console.ReadLine();
            }

If you use response.Content.ToString() it is actually converting the datatype of the Content to string so you will get System.Net.Http.StreamContent