Specifying a custom DateTime format when serializing with Json.Net
You could use this approach:
public class DateFormatConverter : IsoDateTimeConverter
{
public DateFormatConverter(string format)
{
DateTimeFormat = format;
}
}
And use it this way:
class ReturnObjectA
{
[JsonConverter(typeof(DateFormatConverter), "yyyy-MM-dd")]
public DateTime ReturnDate { get;set;}
}
The DateTimeFormat
string uses the .NET format string syntax described here: https://docs.microsoft.com/en-us/dotnet/standard/base-types/custom-date-and-time-format-strings
It can also be done with an IsoDateTimeConverter
instance, without changing global formatting settings:
string json = JsonConvert.SerializeObject(yourObject,
new IsoDateTimeConverter() { DateTimeFormat = "yyyy-MM-dd HH:mm:ss" });
This uses the JsonConvert.SerializeObject
overload that takes a params JsonConverter[]
argument.
You are on the right track. Since you said you can't modify the global settings, then the next best thing is to apply the JsonConverter
attribute on an as-needed basis, as you suggested. It turns out Json.Net already has a built-in IsoDateTimeConverter
that lets you specify the date format. Unfortunately, you can't set the format via the JsonConverter
attribute, since the attribute's sole argument is a type. However, there is a simple solution: subclass the IsoDateTimeConverter
, then specify the date format in the constructor of the subclass. Apply the JsonConverter
attribute where needed, specifying your custom converter, and you're ready to go. Here is the entirety of the code needed:
class CustomDateTimeConverter : IsoDateTimeConverter
{
public CustomDateTimeConverter()
{
base.DateTimeFormat = "yyyy-MM-dd";
}
}
If you don't mind having the time in there also, you don't even need to subclass the IsoDateTimeConverter. Its default date format is yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFFFFFK
(as seen in the source code).
Also available using one of the serializer settings overloads:
var json = JsonConvert.SerializeObject(someObject, new JsonSerializerSettings() { DateFormatString = "yyyy-MM-ddThh:mm:ssZ" });
Or
var json = JsonConvert.SerializeObject(someObject, Formatting.Indented, new JsonSerializerSettings() { DateFormatString = "yyyy-MM-ddThh:mm:ssZ" });
Overloads taking a Type are also available.