marc_s
marc_s

Reputation: 755023

RestSharp can't properly auto-deserialize my JSON response - but JSON.NET can - why?

I have an odd issue with JSON here. I'm calling a REST web service from my C# code using RestSharp (v104.4), and the call works fine.

The issue is with the JSON that gets returned - if I let RestSharp "automatically" decode it - it doesn't work. If I deserialize the JSON I get back manually, using JSON.NET, it works just fine. Why?

My RestSharp request:

RestRequest request = new RestRequest(MyUrl, Method.GET);
request.AddHeader("Authorization", "Bearer " + token);

IRestResponse<JsonResponse> response = _restClient.Execute<JsonResponse>(request);

This is the raw JSON I get back from this call:

{ "roomURL":"https://dev.mycompany.com/room/abc123", "text":"Click here. ....." }

Using this class, I am trying to have RestSharp automatically deserialize this response:

public class JsonResponse {
    public string RoomUrl { get; set; }
    public string Text { get; set; }
}

But using RestSharp - the response.Data I get back has a null value for RoomUrl.

However, if I use JSON.NET to manually deserialize the response into a JsonResult, both pieces of information (RoomUrl and Text) are properly recognized - no issues at all.

var result = JsonConvert.DeserializeObject<JsonResponse>(response.Content);

Here, result.RoomUrl gets the returned URL without any hitch.

I'm just a bit baffled why RestSharp doesn't properly deserialize the JSON returned into a JsonResponse object - any ideas?

I also tried putting a [JsonProperty("roomURL")] on the RoomUrl string in the JsonResponse - but that doesn't make any difference, it seems.

Upvotes: 1

Views: 1628

Answers (1)

marc_s
marc_s

Reputation: 755023

Problem has been solved after posting to the RestSharp Google Group.

RestSharp as of v103 doesn't use JSON.NET anymore, but its own JSON deserializer - which handles certain things slightly differently.

The name roomURL in the JSON response I got wasn't being automatically "picked up" by the RestSharp JSON deserializer - but using a DeserializeAs attribute on my response class solved the issue:

public class JsonResponse {
    [DeserializeAs(Name = "roomURL")]
    public string RoomUrl { get; set; }
    public string Text { get; set; }
}

Now the JSON response from my request gets automatically deserialized as expected, and I can go about using it.

Thanks to Andrew Young in the RestSharp Google Group for solving this!

Upvotes: 3

Related Questions