JSON序列化输出具有c#转义格式



我正试图从我的客户端发布一个更新的对象到REST服务器API。我正在使用RestSharp,并将对象的JSON表示添加到请求的主体中。但是,序列化对象的字符串表示格式错误。服务器拒绝。

我的请求看起来像这样(我使用Fiddler得到它)

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}"

我已经尝试用Json序列化我的对象。. NET、RestSharp的内部Json序列化器以及来自System.Web.Script.Serialization的JavaScriptSerializer。它们都以这种格式返回字符串。我知道这种格式的原因是因为c#转义双引号,所以它可以在里面正确地显示它,但我不明白我应该如何将它传递给我的请求,没有这种转义格式。我知道服务器可以接受正确格式的JSON。

我要序列化的对象看起来像这样

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

编辑:将我的解决方案从这里移到答案

我刚刚在这里读了关于这个问题的另一个主题。问题是我序列化了对象两次。

不是

request.AddBody(JsonConvert.SerializeObject(priceListItem));
我应该用
request.AddBody(priceListItem);

不管怎样,也许它会帮助别人。然而,我发现对象是自动序列化的,这很奇怪。

我也有这个问题,我的解决办法是用Newtonsoft创建一个JObject并传递它。

:

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

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

第一种情况是我的第二选择,但我认为Newtonsoft中有一个bug,其中JObject。FromObject忽略JsonSerializer中的DateFormatString

最新更新