Filter Json Using C#

Asked

Viewed 195 times

1

I have this script in c# that makes me recover a token from an external api to mine that I am developing. Until then, I managed to recover without problems the parameters of this api (the token is within these parameters) however I only need the token and not the other parameters q it is passing me. How do I recover/filter token only ?

Attached below is the script I developed and what was returned to me by the api (what is between the red boxes are the parameters I don’t need).

public async Task<string> GetToken()
    {
        var builder = new ConfigurationBuilder()
             .SetBasePath(Directory.GetCurrentDirectory())
             .AddJsonFile($"appsettings.json");
        var config = builder.Build();

        var username = config.GetSection("SindiOnibus:username").Value;

        var password = config.GetSection("SindiOnibus:password").Value;

         _Url = config.GetSection("SindiOnibus:Url").Value;

         using (var client = new HttpClient())
        {

        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(
                new MediaTypeWithQualityHeaderValue("application/json")); 

        var formContent = new FormUrlEncodedContent(new[]
            {
                new KeyValuePair<string, string>("username", username), 
                new KeyValuePair<string, string>("password", password) 
            });

          HttpResponseMessage respToken = await client.PostAsync(
                _Url, formContent); 

           return await respToken.Content.ReadAsStringAsync();
        }
    }

Where do I retrieve the token:

string token = await GetToken();
Client.DefaultRequestHeaders.Add("Authorizarion", $"Bearer {token}");

Return of the Api: inserir a descrição da imagem aqui

"{\r\n  \"access_token\": \"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1bmlxdWVfbmFtZSI6IkdPTkVUIiwianRpIjoiYzA1ZjBhYTgtZWY5Yy00ZTg5LTkzZWYtMjAzNTU2Nzk0YzFkIiwiaWF0IjoxNTczNDkyMzQzLCJodHRwOi8vc2NoZW1hcy5taWNyb3NvZnQuY29tL3dzLzIwMDgvMDYvaWRlbnRpdHkvY2xhaW1zL3JvbGUiOiJHT05FVCIsImh0dHA6Ly9zY2hlbWFzLnhtbHNvYXAub3JnL3dzLzIwMDUvMDUvaWRlbnRpdHkvY2xhaW1zL25hbWUiOiJHT05FVCIsImV4cCI6MTU3MzQ5MjQwMywiaXNzIjoiSXNzdWVyIiwiYXVkIjoiQXVkaWVuY2UifQ.nykUMmCgN4GiDY2yuagt_mls8Qs9N8HfFD3h30M5lyc\",\r\n  \"expires\": \"2019-11-11T14:13:23.2756-03:00\",\r\n  \"usuario\": {\r\n    \"id\": **,\r\n    \"nome\": \"****\"\r\n  }\r\n}"
  • 1

    You can create a class with all these properties to deserialize your string. And after deserialized you can take any property value.

1 answer

0


You can create a class that represents json and deserialize it in this class, or deserialize in an anonymous object:

You will need to reference the library Newtonsoft.Json

static void Main(string[] args)
{
    string json = "{\r\n  \"access_token\": \"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1bmlxdWVfbmFtZSI6IkdPTkVUIiwianRpIjoiYzA1ZjBhYTgtZWY5Yy00ZTg5LTkzZWYtMjAzNTU2Nzk0YzFkIiwiaWF0IjoxNTczNDkyMzQzLCJodHRwOi8vc2NoZW1hcy5taWNyb3NvZnQuY29tL3dzLzIwMDgvMDYvaWRlbnRpdHkvY2xhaW1zL3JvbGUiOiJHT05FVCIsImh0dHA6Ly9zY2hlbWFzLnhtbHNvYXAub3JnL3dzLzIwMDUvMDUvaWRlbnRpdHkvY2xhaW1zL25hbWUiOiJHT05FVCIsImV4cCI6MTU3MzQ5MjQwMywiaXNzIjoiSXNzdWVyIiwiYXVkIjoiQXVkaWVuY2UifQ.nykUMmCgN4GiDY2yuagt_mls8Qs9N8HfFD3h30M5lyc\",\r\n  \"expires\": \"2019-11-11T14:13:23.2756-03:00\",\r\n  \"usuario\": {\r\n    \"id\": \"**\",\r\n    \"nome\": \"****\"\r\n  }\r\n}";

    var definition = new { access_token = "" };

    var result = JsonConvert.DeserializeAnonymousType(json, definition);

    Console.WriteLine(result.access_token);
}

It is also possible to do without an anonymous object definition:

dynamic result = JsonConvert.DeserializeObject<dynamic>(json);

Obs.: In the user id field, spoke " around *, because it gives error in deserialization.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.