Home > Enterprise >  How to capture response after calling REST API?
How to capture response after calling REST API?

Time:03-30

I am using RestSharp to call REST API as

public async Task<IActionResult> getoutput()
{
  var client = new RestClient("....");
  var request = new RestRequest(".....");
  
  var response = await client.ExecuteAsync(request);
  return Ok(response.Content);
}

My response is like

{
  "number" : 567889
}

I want to get that number 567889 and save it into variable in my controller. But I am not able to do so.

I tried with

var answer = response.Content;

But it is showing the JSON.

Can somebody please help me out?

CodePudding user response:

you can create a class for your data

public class Answer
{
public int number {get;set;}
}

and action

var response = await client.ExecuteAsync(request);
Answer answer= JsonConvert.DeserializeObject<Answer>(response.Content);

int number=answer.number;

  return Ok(answer);

or if for some reason you don't want to create a class, you can parse a json string

var response = await client.ExecuteAsync(request);

int _number= (int) JObject.Parse(response.Content)["number"]

  return Ok( new { number= _number} );
  • Related