【问题标题】:Json RestSharp deserilizing Response Data nullJson RestSharp 反序列化响应数据 null
【发布时间】:2015-06-26 14:30:14
【问题描述】:

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

【问题讨论】:

  • 我路过这个。就我而言,我创建了一个带参数的新构造函数,但我忘记了它创建了一个不带参数的构造函数。

标签: c# json restsharp


【解决方案1】:

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

【讨论】:

  • 谢谢我改变了类,现在可以了:client.AddHandler("*", new JsonDeserializer()); IRestResponse response2 = client.Execute(request); ToDo td = response2.Data;
  • @ThomasKaemmerling 很高兴听到这个消息!如果我的回答对您有所帮助,将不胜感激。 meta.stackexchange.com/questions/23138/…
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-08
相关资源
最近更新 更多