Rest Sharp没有序列化日期
本文关键字:序列化 日期 Sharp Rest | 更新日期: 2023-09-27 18:30:12
当然,最新Restsharp中的默认值应该能够序列化`Datetime。
以下是我的请求构建
var request = new RestRequest(Method.POST);
request.RequestFormat = DataFormat.Json;
//request.JsonSerializer = new MyJsonSerializer(); // When applying JSON.Net serialisation
request.Resource = "SaveBooking";
request.AddHeader("Content-Type", "application/json");
request.AddBody(booking);
return Execute<bool>(request);
我已经尝试过实现JSON.NET Serializer,并按照这个问题中的建议与restsharp
集成,该问题链接到他们的笔记。但我也有同样的问题。
它正在构建的JSON如下:
"BookingDate": "2014-11-13T09:31:02.0667967+00:00",
"StartTime": "2014-11-13T10:30:00",
"EndTime": "2014-11-13T17:00:00",
当试图取消序列化时,我得到的错误形式如下。
DateTime content '2014-11-12T16:20:30.4635576Z' does not start with ''/Date(' and end with ')'/' as required for JSON.'.
很明显,它不是在序列化日期。但我不知道为什么。或者如何修复。
我正在使用rest端点进行反序列化
[OperationContract]
[WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, UriTemplate = "/SaveBooking")]
Boolean SaveBooking(RoomBookingEntry Booking);
带参数
public class RoomBookingEntry
{
public DateTime BookingDate { get; set; }
public DateTime StartTime { get; set; }
public DateTime EndTime { get; set; }
}
}
您可以告诉JSON.Net在序列化日期时使用正确的日期,例如:
var settings = new JsonSerializerSettings() { DateFormatHandling = DateFormatHandling.MicrosoftDateFormat };
JsonConvert.SerializeObject(obj, settings);
默认情况下,还有另一个JSON序列化库可以做到这一点:https://www.nuget.org/packages/ServiceStack.Text/
var request = new RestRequest(Method.POST);
request.RequestFormat = DataFormat.Json;
request.Resource = "SaveBooking";
var json = JsonSerializer.SerializeToString(booking);
request.AddParameter("application/json", json, ParameterType.RequestBody);
使用您的项目中可能已经有的Newtonsoft.Json序列化程序。您只需要手动将参数添加到请求中,绕过有故障的RestSharp序列化程序。
var request = new RestRequest(Method.POST);
request.RequestFormat = DataFormat.Json;
request.Resource = "SaveBooking";
request.AddHeader("Content-Type", "application/json");
var settings = new JsonSerializerSettings() { DateFormatHandling=DateFormatHandling.MicrosoftDateFormat };
var json = JsonConvert.SerializeObject(booking,settings);
request.AddParameter("application/json",json,null,ParameterType.RequestBody);
return Execute<bool>(request);
使用此处找到的序列化程序:https://github.com/khalidabuhakmeh/Ducksboard/tree/master/Ducksboard/Serializers
我已经能够让RestSharp
以DataContractJson
期望的格式发送datetime
。
绑定使用:
var request = new RestRequest(Method.POST);
request.RequestFormat = DataFormat.Json;
request.JsonSerializer = new RestSharpDataContractJsonSerializer();
request.Resource = "SaveBooking";
request.AddHeader("Content-Type", "application/json"); // May not be needed
request.AddBody(booking);