Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RestSharp POST Object as JSON

Tags:

json

c#

restsharp

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.

like image 245
OhMyGuruFR Avatar asked Jun 20 '17 07:06

OhMyGuruFR


1 Answers

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;
}
like image 174
phuzi Avatar answered Sep 29 '22 17:09

phuzi