JSON serialized output has C # formatting

I am trying to POST an updated REST server API object from my client. I use RestSharp, and I add the JSON representation of my object to the body of my request. However, my string representation of the serialized object is in the wrong format. The server rejects it.

My query looks something like this (I used Fiddler to get it)

PUT https://myapp.net/api/PriceListItems/151276 HTTP/1.1 Accept: application/json, application/xml, text/json, text/x-json, text/javascript, text/xml User-Agent: RestSharp/104.4.0.0 Content-Type: application/json Host: myapp.net Content-Length: 75 Accept-Encoding: gzip, deflate "{\"Id\":151276,\"AgendaId\":0,\"CurrencyId\":1,\"Code\":\"\",\"Price\":7.0}" 

I tried serializing my object using Json.NET, the RestSharp built-in JSSI editor, and using the JavaScriptSerializer from System.Web.Script.Serialization. Everyone returns a string in this format. I know that the reason for this formatting is that C # avoids double quotes, so it can correctly display it inside, but I don’t understand how I should pass it to my request without this escaped formatting. I know that properly formed JSON is accepted by the server.

The object I'm trying to serialize is as follows

 public class PriceListItem { public static PriceListItem CreatePriceListItem(int id, int agendaId, int currencyId, string code, string unit, decimal price) { var priceListItem = new PriceListItem { Id = id, AgendaId = agendaId, CurrencyId = currencyId, Code = code, Price = price }; return priceListItem; } public int Id { get; set; } public int AgendaId { get; set; } public int CurrencyId { get; set; } public string Code { get; set; } public decimal Price { get; set; } 

EDIT: Moved my solution from here to the answers.

+6
source share
2 answers

I just read another topic on this issue here . The problem was that I was serializing the object twice.

Instead

 request.AddBody(JsonConvert.SerializeObject(priceListItem)); 

I had to use

 request.AddBody(priceListItem); 

Anyway, maybe this will help someone else. It seems strange to me that an object is serialized automatically.

+10
source

I also had this problem, and my workaround was to create a JObject with Newtonsoft and pass this.

Or:

 JObject jBytes = Object.Parse(JsonConvert.SerializeObject(myObject, MyDateTimeFmtString); 

or

 JObject jBytes = JObject.FromObject(myObject, MyJsonSerializer); 

The first case was my second choice, but I think there is an error in Newtonsoft where JObject.FromObject ignores DateFormatString in JsonSerializer.

-1
source

Source: https://habr.com/ru/post/972654/


All Articles