RestSharp POST object as JSON
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 httpPost method with good URI and PTList object, front API is that "name" is null. I think my PTList object is not serializing as valid JSON in the API request, but cannot figure out what is going wrong.
source to share
There are several problems I see.
First, the object you are sending has no public fields, I would simplify the definition too:
public class PTList
{
public PTList() { get; set; }
}
The second problem is that you are setting the header Content-Type
that RestSharp will do by settingrequest.RequestFormat = DataFormat.Json
I would also be tempted to use generics rather than Object
Then your httpPost method will 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;
}
source to share
The default Json serializer used by RestSharp does not serialize private fields. Thus, you can change your class like this:
public class PTList
{
public PTList() { }
public PTList(String name) {
this.name = name;
}
public string name { get; set; }
}
And it will work fine.
If the capabilities of the default serializer aren't enough (as far as I know - you can't even rename properties with it to make it Name
serialized like Name
for example) - you can use a better serializer like JSON. NET as described below here .
source to share
You can try this instead of AddJsonBody:
request.AddParameter ("application / json; charset = utf-8", JsonConvert.SerializeObject (Data), ParameterType.RequestBody);
This is one of the solutions here: How to add json to POST request RestSharp
source to share