我已经在网上搜索了这方面的信息,但大多数结果都是关于创建WCF服务或服务在您控制之下的情况.
我正在为RESTful JSON服务构建一个WCF客户端代理,这是我无法控制的.我正在使用基本的ServiceContract / DataContract模式,并试图让框架尽可能多地完成工作.
大多数情况下,这工作正常,但来自此外部服务的所有日期时间字段都采用特定格式,例如
{"SomeObject":
{"details":"blue and round","lastmodified":"2013/01/02 23:14:55 +0000"}
}
所以我收到一个错误:
There was an error deserializing the object of type MyNamespace.someObject. DateTime content ‘2013/01/02 23:14:55 +0000’ does not start with ‘/Date(‘ and end with ‘)/’ as required for JSON.’.
我的数据是:
namespace Marshmallow.WebServices.ServiceModels
{
[DataContract]
public class SomeObject
{
[DataMember(Name = "details")]
public string Details { get; set; }
[DataMember(Name = "lastmodified")]
public DateTime LastModified { get; set; }
}
}
我的服务合同是:
[ServiceContract]
public interface ICoolExternalApi
{
[OperationContract]
[WebGet(UriTemplate = "/something.json",ResponseFormat = Webmessageformat.Json,BodyStyle = WebMessageBodyStyle.Wrapped)]
[return: MessageParameter(Name = "SomeObject")]
SomeObject GetAccount();
}
我想知道的是,我在哪里可以添加一些代码来定义WCF如何反序列化lastmodified字段(从字符串中生成DateTime对象)?
或者更好的是,定义如何为所有DataContracts反序列化所有DateTime DataMembers.我不想要很多重复的代码.
我也不想诉诸某些第三方反序列化器,也不想通过自定义反序列化方法开始放置其他所有内容,如果可以避免的话.
解决方法
我能想到的两件事:
>将LastModified更改为字符串,然后自己将其转换为Datetime对象.这意味着在对象上为相同的数据公开两个属性.>编写IdispatchMessageInspector以在反序列化发生之前拦截消息,并使用正则表达式按原始消息.它将为您服务中的所有日期提供一站式解决方案.