Json RestSharp deserilizing Response Data null

时间:2015-06-25 12:55:34

标签: c# json restsharp

我使用RestSharp访问Rest API。我希望将数据作为POCO返回。 我的RestSharp客户端看起来像这样:

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;

我的JsonObject类看起来像这样:

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

和Json回复:

{
    "id":4,
    "created_at":"2015-06-18 09:43:15",
    "updated_at":"2015-06-18 09:43:15",
    "name":"Another Random Test"
}

1 个答案:

答案 0 :(得分:15)

根据documentation,RestSharp仅反序列化为属性,并且您正在使用字段。

  

RestSharp使用您的类作为起点,循环遍历每个   公共可访问,可写的财产和搜索   返回数据中的相应元素。

您需要将ToDo课程更改为以下内容:

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; }
}