-1

I'm working on a personal project. Its a C# app that communicates with some web services using an API.

i finally got the first raw data with this few lines:

var client = new RestClient("https://api.abcd.com/token");
            var request = new RestRequest(Method.POST);
            request.AddParameter("username", usr);
            request.AddParameter("password", pass);
            request.AddParameter("grant_type", "password");

and in postman the response (JSON) looks like :

{"access_token":"aaaaaaa","token_type":"bearer","expires_in":899,"refresh_token":"bbbbbbb",".issued":"Fri, 01 May 2020 16:11:36 GMT",".expires":"Fri, 01 May 2020 16:26:36 GMT",".refreshexpires":"Fri, 01 May 2020 17:11:36 GMT"}

my next step is to find the way to separate those key/value pair into different variables in C# so i can work with them.

thank you so much for the help.

Nico AC
  • 7
  • 2
  • A quick stackoverlfow search would have found you a lot of answers to this question. You're attempting to convert a string array back into a C# Dictionary - https://stackoverflow.com/questions/1385421/most-elegant-way-to-convert-string-array-into-a-dictionary-of-strings for example. – Scott May 01 '20 at 20:54
  • i've searched an answer for 2 days.. but nothing worked... until something posted below.. but thanks for the help anyway. – Nico AC May 03 '20 at 23:36

3 Answers3

1

You want to use a JSON deserialiser to do this.

So you would create a class:

public class Response {
  public string accessToken {get; set;)
  public string token_type {get; set;)
  .....
}

And then use something like Newtonsoft.Json (available from NuGet) to deserialise:

using Newtonsoft.Json;

.....

var response = JsonConvert.Deserialise<Response>([RAW TEXT FROM REST CLIENT]);
Glynn Hurrell
  • 602
  • 6
  • 10
1

But I guess for small purpose no need to create a class rather use weakly typed data structure like this:

dynamic responseObject = JsonConvert.DeserializeObject(responseString);
//then use every property like this
responseObject.accessToken ...
responseObject.token_type.....

But you need to use Newtonsoft.Json for this too.

Rithik Banerjee
  • 447
  • 4
  • 16
0

You can look into using Json.Net which will allow you to deserialize the JSON into an object like so. Note you'll need to download the package and then add using Newtonsoft.Json;

{
    "varone":"valueone"
}
public class MyJsonClass
{
    //JsonProperty isn't strictly required but I personally think it helps when trying to deserialize for sanity sake
    [JsonProperty("varone")]
    public string VarOneValue { get; set; } //The value will be "valueone" on deserialization
}
var myobj = JsonConvert.DeserializeObject<MyJsonObject>(JSONDATA);
Console.Write(myobj.VarOneValue); //Will be "valueone"

Nuget CLI: Install-Package Newtonsoft.Json

Page: https://www.newtonsoft.com/json

li223
  • 369
  • 3
  • 11