Here is my 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;
}
}
and my RestSharp POST Request:
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;
}
and when I use the httpPost method with the good URI and a PTList object, the front API anwser that "name" is null. I think that my PTList object is not serialized as a valid JSON in the request for the API, but can't understand what's going wrong.
There are a couple of issues I can see.
The first is that the object you're sending has no public fields, I'd also simplify the definition a little too:
public class PTList
{
public PTList() { get; set; }
}
The second issue is that you're setting the Content-Type
header which RestSharp will do by setting request.RequestFormat = DataFormat.Json
I'd also be tempted to use generics rather than an Object
Your httpPost method would then become:
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With