这是我的类(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/