I use Json.net
to serialize my objects and I want to customize DateTime
output:
Here is a small example:
[DataContract]
class x
{
[DataMember]
[JsonConverter(typeof(IsoDateTimeConverter))]
public DateTime datum = new DateTime(1232, 3, 23);
}
var dtc = new IsoDateTimeConverter();
dtc.DateTimeFormat = "yy";
JsonConvert.SerializeObject(new x(), dtc);
The result is {"datum":"1232-03-23T00:00:00"}
instead of {"datum":"1232"}
.
This works correctly (returning "32"
):
return JsonConvert.SerializeObject(new DateTime(1232, 3, 23), dtc);
Where is the catch?
The catch is that the converter applied via
[JsonConverter(typeof(IsoDateTimeConverter))]
supersedes the converter passed into the serializer. This is documented in Serialization Attributes: JsonConverterAttribute:As a workaround, in the
ReadJson()
andWriteJson()
methods of the applied converter, one could check for a relevant converter in the serializer's list of converters, and if one is found, use it. The decorator pattern can be used to separate this logic from the underlying conversion logic. First, introduce:Then, apply the decorator on top of
IsoDateTimeConverter
as follows:Now the statically applied converter will be superseded as required. Sample fiddle.
Note that, for this specific test case, as of Json.NET 4.5.1 dates are serialized in ISO by default and
IsoDateTimeConverter
is no longer required. Forcing dates to be serialized in a specific format can be accomplished by settingJsonSerializerSettings.DateFormatString
:Sample fiddle. Nevertheless the general question deserves an answer.