1

I am very much out of my element on this. In C# I am writing a method to get data back from a website using REST. Per the documentation on the website I should use something like this:

var client = new RestClient(url + "token");
var request = new RestRequest(Method.POST);

request.AddParameter("application/x-www-form-urlencoded",
                "grant_type=password&username=" + UserName +
                "&password=" + Password +
                "&tenant=" + Company,
                ParameterType.RequestBody);

IRestResponse response = client.Execute(request);

to get a response that looks like this:

{
  "access_token": "generated_token_value",
  "token_type": "bearer",
  "expires_in": 2591999
}

However, I have no earthly clue to how to read that info. I'm assuming that the JSON response is in my "response" variable, but beyond that I'm at a loss. I've done a little digging and have found Json.NET should be helpful, but it's over my head. Their documentation suggests:

Product deserializedProduct = JsonConvert.DeserializeObject<Product>(output);

However if I convert that into something that looks correct for mine (creating a "Responses" Class and then):

Responses responses = JsonConvert.DeserializeObject<Responses>(response);

I get an error in VS under the "response" saying "cannot convert from 'RestSharp.IRestResponse' to 'string'.

I feel like I just need a little nudge to get over this hump.

gilliduck
  • 2,762
  • 2
  • 16
  • 32

3 Answers3

2
Responses responses = JsonConvert.DeserializeObject<Responses>(response.Content);
2

If you go to the repository of RestSharp you'll see that it has special property called Content which contains JSon in a string format.

Now you can use JsonConvert.DeserializeObject<Responses>(response.Content); to retrieve your object.

mrogal.ski
  • 5,828
  • 1
  • 21
  • 30
  • 1
    That did the trick. the Content property did the trick. Now I've got some other work to do, but the key part works. Thanks! – gilliduck May 11 '17 at 14:08
1

Another option could be declaring the response for the out type you're expecting

IRestResponse<Responses> response = client.Execute<Responses>(request);
Stinky Towel
  • 768
  • 6
  • 26