7

i use RestSharp to access a Rest API. I like to get Data back as an POCO. My RestSharp Client looks like this:

var client = new RestClient(@"http:\\localhost:8080");
        var request = new RestRequest("todos/{id}", Method.GET);
        request.AddUrlSegment("id", "4");
        //request.OnBeforeDeserialization = resp => { resp.ContentType = "application/json"; };
        //With enabling the next line I get an new empty object of TODO
        //as Data
        //client.AddHandler("*", new JsonDeserializer());
        IRestResponse<ToDo> response2 = client.Execute<ToDo>(request);
        ToDo td=new JsonDeserializer().Deserialize<ToDo>(response2);

        var name = response2.Data.name;

my Class for the JsonObject looks like this:

public class ToDo
{
    public int id;
    public string created_at;
    public string updated_at;
    public string name;
}

and the Json Response:

{
    "id":4,
    "created_at":"2015-06-18 09:43:15",
    "updated_at":"2015-06-18 09:43:15",
    "name":"Another Random Test"
}
1
  • I passed by this. In my case, I have create a new constructor with parameters, and I forgot it create a constructor without parameter. Commented Aug 27, 2021 at 3:39

1 Answer 1

18

Per the documentation, RestSharp only deserializes to properties and you're using fields.

RestSharp uses your class as the starting point, looping through each publicly-accessible, writable property and searching for a corresponding element in the data returned.

You need to change your ToDo class to the following:

public class ToDo
{
    public int id { get; set; }
    public string created_at { get; set; }
    public string updated_at { get; set; }
    public string name { get; set; }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks I changed the class and now this works: client.AddHandler("*", new JsonDeserializer()); IRestResponse<ToDo> response2 = client.Execute<ToDo>(request); ToDo td = response2.Data;
@ThomasKaemmerling Glad to hear it! If my answer helped you, accepting it would be greatly appreciated. meta.stackexchange.com/questions/23138/…

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.