【问题标题】:RestSharp POST Object as JSONRestSharp POST 对象为 JSON
【发布时间】:2017-06-20 15:53:20
【问题描述】:

这是我的课:

public class PTList
{
    private String name;

    public PTList() { }
    public PTList(String name)
    {
        this.name = name;
    }


    public String getName()
    {
        return name;
    }

    public void setName(String name)
    {
        this.name = name;
    }

}

和我的 RestSharp POST 请求:

    protected static IRestResponse httpPost(String Uri, Object Data)
    {
        var client = new RestClient(baseURL);
        client.AddDefaultHeader("X-Authentication", AuthenticationManager.getAuthentication());
        client.AddDefaultHeader("Content-type", "application/json");
        var request = new RestRequest(Uri, Method.POST);

        request.RequestFormat = DataFormat.Json;

        request.AddJsonBody(Data);

        var response = client.Execute(request);
        return response;
    }

当我使用带有良好 URI 和 PTList 对象的 httpPost 方法时,前面的 API anwser 表明“名称”为空。 我认为我的 PTList 对象在 API 请求中未序列化为有效 JSON,但无法理解发生了什么问题。

【问题讨论】:

  • 您可以尝试一些事情,首先通过添加断点或在控制台上显示它来确保您传递的Data 格式有效,其次您可以尝试更简单的类,例如@987654324 @ 具有公共可访问字段名称。
  • AFAIK 序列化将序列化 properties 并且没有属性 => 没有内容,只是像 {} 这样的空对象

标签: c# json restsharp


【解决方案1】:

我可以看到几个问题。

首先是您发送的对象没有公共字段,我也将定义简化一点:

public class PTList
{
    public PTList() { get; set; }
}

第二个问题是您正在设置 Content-Type 标头,RestSharp 将通过设置 request.RequestFormat = DataFormat.Json 来完成此操作

我也很想使用泛型而不是Object

你的 httpPost 方法会变成:

protected static IRestResponse httpPost<TBody>(String Uri, TBody Data)
    where TBody : class, new
{
    var client = new RestClient(baseURL);
    client.AddDefaultHeader("X-Authentication", AuthenticationManager.getAuthentication());
    var request = new RestRequest(Uri, Method.POST);
    request.RequestFormat = DataFormat.Json;
    request.AddJsonBody(Data);

    var response = client.Execute(request);
    return response;
}

【讨论】:

    【解决方案2】:

    你可以试试这个而不是 AddJsonBody:

    request.AddParameter("application/json; charset=utf-8", JsonConvert.SerializeObject(Data), ParameterType.RequestBody);

    这是这里的解决方案之一:How to add json to RestSharp POST request

    【讨论】:

      【解决方案3】:

      RestSharp 默认使用的 Json 序列化器不会序列化私有字段。所以你可以像这样改变你的班级:

      public class PTList
      {        
          public PTList() { }
      
          public PTList(String name) {
              this.name = name;
          }
      
          public string name { get; set; }
      }
      

      它会正常工作的。

      如果默认序列化程序的功能还不够(据我所知——你甚至不能用它重命名属性,例如将Name 序列化为name)——你可以使用更好的序列化程序,比如 JSON。 NET,例如描述的here

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-04-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多