c# - RestSharp POST 对象作为 JSON

标签 c# json restsharp

这是我的类(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“名称”为空。 我认为我的 PTList 对象未在 API 请求中序列化为有效的 JSON,但无法理解出了什么问题。

最佳答案

我可以看到几个问题。

首先是您发送的对象没有公共(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;
}

关于c# - RestSharp POST 对象作为 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44646666/

相关文章:

java - 如何使用 jQuery 将 JSON 数据发布到 Struts2 Action 类

python - 从tweets json格式文件解析的有效方法

asp.net - 使用 RestSharp/JSON.NET 反序列化自定义数组

c# - RestSharp是否有缓存

c# - 以类名作为根元素序列化对象

c# - 正则表达式挑战 : Modify this line of C#

c# - 在 C# 中过滤字符串时忽略重音字母

javascript - Javascript 中的 JSON 对象排序

c# - 使用 C# (Xamarin) 编写 Android 应用程序

c# - BackgroundWorker:从 DoWorkEventHandler 调用的每个方法是否都在后台线程中运行?