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
CodePudding user response:
You are trying to deserialize the whole RESTSharp response object, not only it's json content.
The string representation of the response content is available at the Content property of your response variable, try deserializing that instead:
var deserial = JsonSerializer.Deserialize<Posts>(response.Content);
See the restsharp source code, line 56: https://github.com/restsharp/RestSharp/blob/dev/src/RestSharp/Response/RestResponseBase.cs
CodePudding user response:
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.