RestSharp POST 对象作为 JSON

RestSharp POST Object as JSON

这是我的 class:

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 "name" 为空。 我认为我的 PTList 对象在 API 的请求中没有序列化为有效的 JSON,但无法理解出了什么问题。

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

public class PTList
{        
    public PTList() { }

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

    public string name { get; set; }
}

它会很好地工作。

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

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

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

这是这里的解决方案之一:

我可以看到几个问题。

首先是您发送的 object 没有 public 字段,我也将定义稍微简化一下:

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

第二个问题是您正在设置 Content-Type header,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;
}