Json RestSharp 反序列化响应数据为 null

7

我使用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"
}

我路过了这个。在我的情况下,我创建了一个带有参数的新构造函数,并忘记了创建一个没有参数的构造函数。 - Fabio Souza
1个回答

18

根据文档,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; }
}

谢谢,我已经更改了类,现在它可以工作了: client.AddHandler("*", new JsonDeserializer()); IRestResponse<ToDo> response2 = client.Execute<ToDo>(request); ToDo td = response2.Data; - Thomas Kaemmerling
4
@ThomasKaemmerling 很高兴听到这个消息!如果我的回答有帮助到你,请考虑接受它,这将非常感激。 http://meta.stackexchange.com/questions/23138/how-to-accept-the-answer-on-stack-overflow - David L

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接