0

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);
    }
}

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for reply but that also didn't work. Now I got this error "{\"type\":\"Bad Request\",\"message\":\"Required parameter missing: product\"}".

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.