RestSharp POST Object as JSON



这是我的类:

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,但无法理解出了什么问题。

我可以看到几个问题。

首先是你发送的对象没有公共字段,我也会稍微简化定义:

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

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

请求。AddParameter("application/json;charset=utf-8", JsonConvert.SerializeObject(Data(, ParameterType.RequestBody(;

这是这里的解决方案之一:如何将json添加到RestSharp POST请求中

默认情况下,

RestSharp 使用的 Json 序列化程序不会序列化私有字段。所以你可以像这样改变你的类:

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

它会正常工作。

如果默认序列化程序的功能还不够(据我所知 - 您甚至无法使用它重命名属性,例如Name序列化为name( - 您可以使用更好的序列化程序,例如 JSON.NET,例如此处描述的那样。

最新更新