【发布时间】:2013-08-05 14:14:47
【问题描述】:
我有一个接收“时间戳”列表的 WCF 方法
public bool SyncTimestamps(IList<Timestamp> timestamps)
在我的一生中,我无法让客户端以对使用 RestSharp 感到满意的格式将值传递给主机。问题似乎与日期格式有关。
尝试 1
var request = new RestRequest("Timestamp/SyncTimestamps", Method.POST);
request.RequestFormat = DataFormat.Json;
request.AddBody(timestamps);
输出 1
"[{\"ID\":1,\"JobId\":654321,\"TimestampSelected\":\"2013-08-05T13:51:13.6201529Z\",\"TimestampActual\":\"2013-08-05T13:51:13.6201529Z\",\"Type\":1,\"Active\":false}]"
错误 1
日期时间内容“2013-08-05T13:51:13.6201529Z”不以 '/Date(' 并根据 JSON 的要求以 ')/' 结尾。'
我读到这是 RestSharp 序列化程序的问题,所以我用 Json.Net 替换它会产生稍微不同的日期字符串。
尝试 2
var request = new RestRequest("Timestamp/SyncTimestamps", Method.POST);
request.RequestFormat = DataFormat.Json;
request.AddBody(JsonConvert.SerializeObject(timestamps));
输出 2
{application/json="[{\"ID\":1,\"JobId\":654321,\"TimestampSelected\":\"2013-08-05T14:54:33.9261815+01:00\",\"TimestampActual\":\"2013-08-05T14:54:33.9251814+01:00\",\"Type\":1,\"Active\":false}]"}
错误 2
The exception message is 'Expecting state 'Element'..
Encountered 'Text' with name '', namespace ''. '. See server logs for more details.
The exception stack trace is:
at ReadArrayOfTimestampFromJson(XmlReaderDelegator , XmlObjectSerializerReadContextComplexJson , XmlDictionaryString , XmlDictionaryString , CollectionDataContract )
at System.Runtime.Serialization.Json.JsonCollectionDataContract.ReadJsonValueCore(XmlReaderDelegator jsonReader, XmlObjectSerializerReadContextComplexJson context)
at System.Runtime.Serialization.Json.JsonDataContract.ReadJsonValue(XmlReaderDelegator jsonReader, XmlObjectSerializerReadContextComplexJson context) at
谁能建议一种方法来生成 WCF 服务将乐于接受和反序列化的日期格式? MSDN 上的文档声明需要以下格式。
DateTime 值显示为 JSON 字符串,格式为 “/Date(700000+0500)/”,其中第一个数字(示例中为 700000 提供) 是 GMT 时区的毫秒数,常规 (非夏令时)自 1970 年 1 月 1 日午夜开始的时间。
更新:
我发现作为 JSON.Net 一部分的设置允许我将日期转换为 WCF 似乎要求的格式。
var settings = new JsonSerializerSettings() { DateFormatHandling = DateFormatHandling.MicrosoftDateFormat };
JsonConvert.SerializeObject(obj, settings);
这似乎完成了创建序列化字符串的工作。
{application/json="[{\"ID\":1,\"JobId\":654321,\"TimestampSelected\":\"\\/Date(1375713542908+0100)\\/\",\"TimestampActual\":\"\\/Date(1375713542908+0100)\\/\",\"Type\":1,\"Active\":false}]"}
但是,我的服务仍然拒绝此操作,并显示“异常消息是 'Expecting state 'Element'..”
【问题讨论】: