0

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?

Christian Baumann
  • 3,188
  • 3
  • 20
  • 37
blac040
  • 127
  • 2
  • 9
  • The [documentation describes how to deal with response](https://restsharp.dev/intro.html#response), including how to deserialize the response to an object. Did you refer to the documentation? Try to implement deserializing to a specific type? Have you declared a type that matches the shape of the JSON you're getting back? – mason Mar 28 '22 at 17:36

1 Answers1

1

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} );
Serge
  • 40,935
  • 4
  • 18
  • 45