NoWoL
July 18, 2016, 12:52pm
1
Hi,
We currently use the XSD duration format for TimeSpan and I was wondering if there is a way to use the .Net format for one DTO…something like adding an attribute to specify the format of the property.
I could handle the serialization myself by changing the property type from TimeSpan to string but I would like to know if there is a more elegant way to change the TimeSpan serialization format for a specific request.
Thanks
NoWoL
July 18, 2016, 1:24pm
2
Or is it possible to add new fields when serializing (I don’t care about deserializing in this case).
For example, if I have the following DTO:
public class Hello
{
public TimeSpan TS {get;set;}
}
Is there a way to automatically add a new property (at runtime/serialization) that would create this object
(json)
{
"TS": "PT30S",
"TS_net": "00:00:30"
}
You can customize TimeSpan serialization to use standard .net form by several ways:
By adding ?jsconfig=tsh:sf
to the end of query string. For example request query will look: yourdomain.com is available for purchase - Sedo.com
Enable Standard Format serializing for TimeSpan
directly in your service.
public object Any(HelloRequest request)
{
using (JsConfig.CreateScope("tsh:sf"))
{
return new Hello { TS = TimeSpan.FromSeconds(30)}.ToJson();
}
}
Or by using your own custom TimeSpan
serializer in service:
public object Any(HelloRequest request)
{
using (JsConfig.CreateScope(String.Empty)
{
JsConfig<TimeSpan>.SerializeFn = time => time.ToString(@"hh\:mm\:ss");
return new Hello { TS = TimeSpan.FromSeconds(30)}.ToJson();
}
}
For more information you can read this article:
NoWoL
July 18, 2016, 3:04pm
4
Option #1 will work for my use case.
Thanks!