Shrodinger
Shrodinger

Reputation: 159

Deserialize JSON with RestSharp

I am making a request to http://api.weatherapi.com/v1/current.json using RetSharp like so:

        var request = new RestSharp.Serializers.Newtonsoft.Json.RestRequest();
        request.AddHeader("content-type", "application/json");
        var client = new RestClient(URL + urlParameters);
        client.Proxy = WebRequest.DefaultWebProxy; // I was led to believe this will fix my problem of my requests taking minutes on end to execute, but it didn't that much.
        var queryResult = client.Execute(request).Content;
        var response = JsonConvert.DeserializeObject<CurrentJsonResponse>(queryResult);

This works fine but I don't like that I have to make a separate call to JsonConvert, and, supposedly, RestSharp should have support for that kind of thing built-in.

I tried the following:

        var response = client.Execute<CurrentJsonResponse>(request).Data; // returns a CurrentJsonResponse object with null properties.

        request.JsonSerializer = new NewtonsoftJsonSerializer(); // I put it at the very start, but doesn't help.

        var jsonDeserializer = new JsonDeserializer();
        client.AddHandler("application/json", jsonDeserializer); // Second verse, same as the first.

        var response = client.Execute<object>(request).Data; // Correctly creates an annonymous object that has the right properties/information but it's not exactly what I'm going for. As I wanted it strongly-typed.

Nothing worked. How can I deserialize the json response I get with RestSharp explicitly, without a separate call to Newtonsoft. I have downloaded the RestSharp.Serializers.Newtonsoft.Json nuget.

Upvotes: 2

Views: 9658

Answers (2)

Shahriar Hossain
Shahriar Hossain

Reputation: 1293

The default deserialization should work fine, I only had to change some serialization settings during post request.

   var request = new RestRequest();    
   var restClient = new RestClient(endPoint);

   request.Method = Method.GET;

   request.AddHeader("Content-Type", "application/json");

   var response = restClient.Execute<T>(request);

       if (response.ErrorException != null)
       {
            //log the exception
            //throw exception;
       }
   return response.Data;

In my experience, I have seen the default deserialization does not produce the expected result, if the mapping class is not proper. Make sure, you have correctly converted the JSON response to its corresponding c# class.

Upvotes: 0

Guru Stron
Guru Stron

Reputation: 143213

In your second attempt try changing

 var jsonDeserializer = new JsonDeserializer();
 client.AddHandler("application/json", jsonDeserializer);

To

client.AddHandler("application/json", () => new RestSharp.Serializers.Newtonsoft.Json.NewtonsoftJsonSerializer());

And call:

var response = client.Execute<CurrentJsonResponse>(request).Data;

Upvotes: 2

Related Questions