Reputation: 338
I'm trying to use RestSharp to POST some data, however I'm encountering an error with my JSON content in the IRestResponse response.
Error: "{"status":"error","message":"Invalid input JSON on line 1, column 96: Unexpected character ('e' (code 101)): was expecting comma to separate Object entries",...}"
From the message I assume I'm missing a comma at the end of the "content" line to separate the objects but can't figure out how to do it? Or do I need to place my name/value pairs into their own objects?
var client = new RestClient("https://api.com/APIKEY");
var request = new RestRequest(Method.POST);
request.AddHeader("accept", "application/json");
request.AddHeader("content-type", "application/json");
request.AddParameter("application/json", "{\"properties\":{" +
"\"pipeline\":\"0\"," +
"\"content\":\"<b>Email: </b>\"" + user.Email + "\"<br/><b>Error: </b>\"" + string.Join("<br/>", type.Name.Split(',').ToList()) + "\"<br/><b>UserId: </b>\"" + user.userId + "\"<br/><b>RequestId: </b>\"" + callbackData.idReference +
"\"subject\":\"Error for\"" + user.FirstName + " " + user.LastName +
"\"owner_id\":\"001\"}}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
Upvotes: 0
Views: 1333
Reputation: 13060
You should never manually build your own JSON! You should use an (anonymous) object and a dedicated JSON serialiser like Json.Net.
That being said RestSharp allows you to specify an object as the parameter value for AddParameter
but you should probably be using AddJsonBody
for the request body.
There are several mistakes in your manual JSON generation like missing quotes and commas at the end of the "content"
and "subject"
lines.
var client = new RestClient("https://api.com/APIKEY");
var request = new RestRequest(Method.POST);
request.AddHeader("accept", "application/json");
request.AddHeader("content-type", "application/json");
var parameter = new
{
properties = new {
pipeline = "0",
content = $"<b>Email: </b>\"{user.Email}\"<br/><b>Error: </b>\"{string.Join("<br/>", type.Name.Split(',').ToList())}\"<br/><b>UserId: </b>\"{user.userId}\"<br/><b>RequestId: </b>\"{callbackData.idReference}",
subject = $"Error for \"{user.FirstName} {user.LastName}\"",
owner_id = "001"
}
};
request.AddJsonBody(parameter)
IRestResponse response = client.Execute(request);
Doing it this way is much less error prone.
Upvotes: 3