JDraz
JDraz

Reputation: 11

RestSharp Post Json Object

I am trying to Post a simple Json object using RestSharp to add a new product. I'm getting an error response from the server "{"status":400,"error":"There was a problem in the JSON you submitted: unexpected character (after ) at line 1, column 2 [parse.c:724] in '{'product':{'name':'Product name','opt1':'Colour'}}"}"

My code:

////
var json = "{\'product\':{\'name\':\'Product name\',\'opt1\':\'Colour\'}}";

IRestClient restClient = new RestClient();
IRestRequest request = new RestRequest()
{
    Resource = "https://api.targetsite.com/products/"
};

request.AddHeader("Content-Type", "application/json");
request.AddHeader("Accept", "application/xml");
request.AddHeader("authorization", "Bearer " + token);
request.RequestFormat = DataFormat.Json;
request.AddJsonBody(json);

IRestResponse response = restClient.Post(request);
////

I managed to achive the result I wanted using a curl statment but I would like to do it using RestSharp.

Curl statment -

curl -X POST -H "Content-type: application/json" -H "Authorization: Bearer <ACCESS_TOKEN>"
https://api.targetsite.com/products/ -d '{"product":{"name":"Product name","opt1":"Colour"}}'

This HttpClient call also works fine

   using (var httpClient = new HttpClient())
{
    using (var request = new HttpRequestMessage(new HttpMethod("POST"), "https://api.targetsite.com/products/"))
    {
        request.Headers.TryAddWithoutValidation("Authorization", "Bearer <ACCESS_TOKEN>"); 

        request.Content = new StringContent("{\"product\":{\"name\":\"Product name\",\"opt1\":\"Colour\"}}");
        request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json"); 

        var response = await httpClient.SendAsync(request);
    }
}

Upvotes: 0

Views: 3448

Answers (1)

Razvan P.
Razvan P.

Reputation: 11

It looks like a limitation on the API you are calling.

When you send the json with curl, you're using different delimiters (" instead of ').

My guess is that the API you're calling doesn't properly deserialize the JSON when ' is used.

What you can try is replacing the escaped ' with " or replace this line in your code : request.AddJsonBody(json) with request.AddJsonBody(Newtonsoft.Json.JsonConvert.DeserializeObject(json)) provided that you have installed the newtonsoft package.

Upvotes: 1

Related Questions