Home > Software engineering >  Deserialize a JsonResult from C#
Deserialize a JsonResult from C#

Time:07-19

I access a REST API with this code :

public async Task<IActionResult> NetExplorerAPI(string AdresseAPI, object Requete, RestSharp.Method Methode)
    {
        var client = new RestClient(AdresseAPI);

        var request = new RestRequest();
        request.Method = RestSharp.Method.Post;
        request.AddJsonBody(Requete);
        request.AddHeader("Accept", "application/json");
        
        //request.AddHeader("Authorization", "Bearer a844024a4e744182aeaa62dd6347b9049f9ba35650339d2b9362e1bf03a92ac0");
        //IRestResponse response = await client.ExecuteAsync(request);

        RestResponse response = await client.ExecuteAsync(request);
        
        JsonResult jr = new JsonResult(response);
        
        return (jr);
    }

I want to deserialize the JsonResult to get the token in a string :

{ "token": "med6RRIikrZ-2tua9jUa6pVZubnPvhqSH6wHvtkH42TNfJGXOaI-GioUKPvfbhP7XiGG6UgjCzUnJt87kwsljQBAKEb" }

But When I serialize the JsonResult I get a lot of items I don't need to :

string s = JsonConvert.SerializeObject(jr);

{"ContentType":null,"SerializerSettings":null,"StatusCode":null,"Value":{"ContentType":null,"SerializerSettings":null,"StatusCode":null,"Value":{"Request":{"AlwaysMultipartFormData":false,"MultipartFormQuoteParameters":false,"FormBoundary":null,"Parameters":[{"DataFormat":0,"ContentEncoding":null,"Name":"","Value":{"user":"[email protected]","password":"S@r@line2004"},"Type":3,"Encode":false,"ContentType":"application/json"},{"Name":"Accept","Value":"application/json","Type":2,"Encode":false,"ContentType":null}],"Files":[],"Method":1,"Timeout":0,"Resource":"","RequestFormat":0,"RootElement":null,"OnBeforeDeserialization":null,"OnBeforeRequest":null,"OnAfterRequest":null,"Attempts":1,"CompletionOption":0,"ResponseWriter":null,"AdvancedResponseWriter":null},"ContentType":"application/json","ContentLength":103,"ContentEncoding":[],"Content":"{"token":"wlK4LIRpOxqKOwJ2Hs554l5-WI--IrqHW7TECZ3YtdS-RpzDuQGaQeLI0qjo8NzaSPhCUYaarBcXstrI5sPlXkwCmk9"}","StatusCode":200,"IsSuccessful":true,"StatusDescription":"Ok","RawBytes":"eyJ0b2tlbiI6IndsSzRMSVJwT3hxS093SjJIczU1NGw1LVdJLS1JcnFIVzdURUNaM1l0ZFMtUnB6RHVRR2FRZUxJMHFqbzhOemFTUGhDVVlhYXJCY1hzdHJJNXNQbFhrd0NtazkifQ==","ResponseUri":"https://patrimoine-click.netexplorer.pro/api/auth","Server":"Apache","Cookies":[],"Headers":[{"Name":"Date","Value":"Tue, 19 Jul 2022 06:40:36 GMT","Type":2,"Encode":false,"ContentType":null},{"Name":"Server","Value":"Apache","Type":2,"Encode":false,"ContentType":null},{"Name":"Pragma","Value":"no-cache","Type":2,"Encode":false,"ContentType":null},{"Name":"Cache-Control","Value":"no-store, must-revalidate, no-cache","Type":2,"Encode":false,"ContentType":null},{"Name":"X-NetExplorer-Version","Value":"7.4.4.12","Type":2,"Encode":false,"ContentType":null},{"Name":"Access-Control-Allow-Origin","Value":"*","Type":2,"Encode":false,"ContentType":null},{"Name":"X-UA-Compatible","Value":"IE=edge,chrome=1","Type":2,"Encode":false,"ContentType":null},{"Name":"Connection","Value":"close","Type":2,"Encode":false,"ContentType":null},{"Name":"X-Content-Type-Options","Value":"nosniff","Type":2,"Encode":false,"ContentType":null},{"Name":"Transfer-Encoding","Value":"chunked","Type":2,"Encode":false,"ContentType":null}],"ContentHeaders":[{"Name":"Expires","Value":"Thu, 19 Nov 1981 08:52:00 GMT","Type":2,"Encode":false,"ContentType":null},{"Name":"Content-Type","Value":"application/json","Type":2,"Encode":false,"ContentType":null},{"Name":"Content-Length","Value":"103","Type":2,"Encode":false,"ContentType":null}],"ResponseStatus":1,"ErrorMessage":null,"ErrorException":null,"Version":"1.1","RootElement":null}}}

I don't know how to get the "content" item.

Thanks by advance,

CodePudding user response:

From RestSharp's official QuickStart:

When using typed ExecuteAsync<T>, you get an instance of RestResponse<T> back, which is identical to RestResponse but also contains the T Data property with the deserialized response.

None of ExecuteAsync overloads throw if the remote server returns an error. You can inspect the response and find the status code, error message, and, potentially, an exception.

Extensions like GetAsync<T> will not return the whole RestResponse<T> but just a deserialized response. These extensions will throw an exception if the remote server returns an error. The exception will tell you what status code was returned by the server.

It looks like you have to choices:

  1. Use client.ExecuteAsync and then response.Data
  2. Use client.GetAsync<T>

For client.GetAsync you'll need a new type. For exmaple

public class MyTokenClass { public string token {get; set;} } 

and then var t = await client.GetAsync<MyTokenClass>().

CodePudding user response:

I think this is what you looking for let me know if you need something specific.

string theToken = JObject.Parse(response.Content)["token"].ToString();

CodePudding user response:

When you get a Response object from ExecuteAsync, response is already deserialized into c# Response class, but Content is not. In this case Content contains a json string. You can parse the string to get a token (or deserialize it if you create a custom class)

This code will return { "token": "med6RRIikrZ-2tua9jUa6p...} as an ActionResult

string token = (string)JObject.Parse(response.Content)["token"];
return Ok( new { token = token});
  • Related