Home > Back-end >  How to get json response form http get request
How to get json response form http get request

Time:09-18

I'm getting a data from API and converting it to json string as follows -

   [HttpGet]
    public async Task<JProperty[]> GetSomeDataAsync()
    {
        try
        {
            HttpClient client = new HttpClient();
            client.BaseAddress = new Uri("myURI");
            HttpResponseMessage response = await client.GetAsync(client.BaseAddress);
            response.EnsureSuccessStatusCode();
            //string responseBody = await response.Content.ReadAsStringAsync();
            if (response != null)
            {
                jsonString = await response.Content.ReadAsStringAsync();
                 jsonObject = JObject.Parse(jsonString);
                //return JsonConvert.DeserializeObject(jsonString);
                //return JsonConvert.DeserializeObject<object>(jsonString);
               var x = jsonObject.Descendants().OfType<JProperty>().Where(p => p.Name == "observations")
                     .ToArray();
                return x;

            }
            else
            {
                throw new ArgumentNullException();
            }
        }
        catch (Exception ex)
        {
        }

The above code is written in Controller and response is sent to Angular Component which contains the following code -

 public economicData: any | null = null;
 public value: any;
 chart: any=[];

 constructor(http: HttpClient, @Inject('BASE_URL') baseUrl: string) 
 {
 http.get<any>(baseUrl   'somedata', { context: new 
 HttpContext().set(IsCacheable, true) 
 }).subscribe(result => { 
 this.economicData = result;
 console.log(this.economicData);
 this.value = this.economicData.observations.map((observations: 
 any) => { 
 observations.value });
 console.log(this.value);
  

 }, error => console.error(error));
 }`

I'm able to see data in array during debug mode in controller. But I'm not getting any data in the objects array in console log nor in the result of component while debugging. Hence I'm not able to map the property present in json to the chart.

Following is the image of output logged in console.log- enter image description here

CodePudding user response:

I'm not sure I completely understand what your question / issue is, but I'll give it a shot.

This code from your segment segment:

this.economicData = result;
console.log(this.economicData);
this.value = this.economicData.observations // other code here

Based on your console log screenshot this.economicData is an array. But, then you try to access a property on it, which I would expect to give an error.

CodePudding user response:

Just look at my example. you have to install newtonsoft nuget package in order this code work.

using (var client = new HttpClient())
{
    client.BaseAddress = new Uri("API URL");
    client.DefaultRequestHeaders.Accept.Clear();
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    
    var inputs = new Parameters() { inputs }; // parameters is a class of your api input parameters
    HttpResponseMessage response = await client.PostAsJsonAsync("Continuation of your API URL", inputs);

    var resultString = await response.Content.ReadAsStringAsync();

    Excel resultJson = JsonConvert.DeserializeObject<your API Output Class>(resultString)!;

    if (response.IsSuccessStatusCode)
    {
        // your code after api response receive.
    }
    else
    {
        Console.WriteLine("Error");
    }
}

if this helped someone, pls upvote and accept this answer. thank you

  • Related