'How to Deserialize response from RestSharp using System.Text.Json?

I am trying to write simple Get operation using RestSharp and trying to use System.Test.Json to deserialize the response.

My Test method is as follows,

    [Test]
    public  void Test1()
    {
        var restClient = new RestClient("http://localhost:3333/");

        var request = new RestRequest("posts/{postid}", Method.Get);

        request.AddUrlSegment("postid", 1);

        var response = restClient.ExecuteGetAsync(request).GetAwaiter().GetResult();

        var deserial = JsonSerializer.Deserialize<Posts>(response);
    }

The Posts model class is as follows,

public class Posts
{
    public string id { get; set; }
    public string title { get; set; }
    public string author { get; set; }
}

But I am getting compellation error in line "var deserial = JsonSerializer.Deserialize(response);"

cannot convert from 'RestSharp.RestResponse' to 'System.Text.Json.JsonDocument' NUnitAPIPractice

If I changed to

var deserial = JsonSerializer.Deserialize<Posts>(response).ToSring();

Then compilation issue is fixed but then after I execute the code then I am getting

    System.Text.Json.JsonException : 'R' is an invalid start of a value. Path: $ | LineNumber: 0 | BytePositionInLine: 0.
      ----> System.Text.Json.JsonReaderException : 'R' is an invalid start of a value. LineNumber: 0 | BytePositionInLine: 0.
  Stack Trace: 
    ThrowHelper.ReThrowWithPath(ReadStack& state, JsonReaderException ex)

Please tell me do I have to use special JSON conversion to convert the RestSharp response to JSON to solve this issue ? Thanks



Solution 1:[1]

RestSharp will deserialize it for you.

var response = await restClient.ExecuteGetAsync<Posts>(request);
var deserialized = response.Data;

Alternatively

var deserialized = await restClient.GetAsync<Posts>(request);

It's always a good idea to refer to the documentation.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Alexey Zimarev