Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Json RestSharp deserilizing Response Data null

Tags:

json

c#

restsharp

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"
}
like image 499
Thomas Kaemmerling Avatar asked Jun 25 '15 12:06

Thomas Kaemmerling


1 Answers

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; }
}
like image 101
David L Avatar answered Oct 22 '22 11:10

David L