I need to replace the DateTime serialization for JSON in WCF REST Self Hosted service. Right now, I'm using something like the following code to do it, but it's definitely not the way to go since it requires manipulating each class.
[DataContract]
public class Test
{
[IgnoreDataMember]
public DateTime StartDate;
[DataMember(Name = "StartDate")]
public string StartDateStr
{
get { return DateUtil.DateToStr(StartDate); }
set { StartDate = DateTime.Parse(value); }
}
}
where my utility function DateUtil.DateToStr does all the formatting work.
Is there any easy way to do it without having to touch the attributes on my classes which have the DataContract attribute? Ideally, there would be no attributes, but a couple of lines of code in my configuration to replace the serializer with one where I've overridden DateTime serialization.
Everything that I've found looks like I have to replace huge pieces of the pipeline.
This article doesn't appear to apply because in I'm using WebServiceHost not HttpServiceHost, which not part of the 4.5.1 Framework.
After long time discussion ,I have find out the solution for it. Please Use the following Code to Solve serialized date..
I hope you have also tried messageformatter in WCF. Since this is long explanation,i am passing on the link to that article.
http://blogs.msdn.com/b/carlosfigueira/archive/2011/05/03/wcf-extensibility-message-formatters.aspx
By default WCF uses DataContractJsonSerializer to serialize data into JSON. Unfortunatelly date from this serializer is in very difficult format to parse by human brain.
To override this behavior we need to write custom IDispatchMessageFormatter. This class will receive all data which should be returned to requester and change it according to our needs.
To make it happen to the operations in the endpoint add custom formatter - ClientJsonDateFormatter:
ClientJsonDateFormatter is simple class which just applies formatter ClientJsonDateFormatter
In the formatter we took imput and serialize it with the changed Serializer:
And to send information to client we need data writer - RawDataWriter. Its implementation is simple:
Applying all code will result in returning date in more friendly format:
To show it in practice I created example in the github branch DateTimeFormatter.
Please check also this answer as very likely you also will need it.
There is a limitation in JSON to convert
DateTime
, specially according to your case.Please see http://msdn.microsoft.com/en-us/library/bb412170(v=vs.110).aspx and read the section
Dates/Times and JSON
To resolve this problem, I simply changed the type of serialization from
JSON
toXML
for all the calls includingDateTime
.