IsoDateTimeConverter 和 JsonSerializerSettings:区分 DateTime 和 DateTimeOffset

IsoDateTimeConverter and JsonSerializerSettings: differentiate DateTime with DateTimeOffset

在我的 C# 模型中,我同时使用 DateTimeDateTimeOffset,例如:

   class Foo 
   {
        public DateTime Date { get; set; }
        public DateTimeOffset CreationDate { get; set; }
   } 

当我序列化到 JSON 时,我是这样做的:

  Foo foo = new Foo();
  foo.Date = DateTime.UtcNow;
  foo.CreationDate = DateTime.UtcNow;

  var isoDateTimeConverter = new IsoDateTimeConverter();
  isoDateTimeConverter.DateTimeFormat = "yyyy'-'MM'-'dd";

  var serializerSettings = new JsonSerializerSettings();
  serializerSettings.Converters.Add(isoDateTimeConverter);

  JsonSerializer serializer = JsonSerializer.Create(serializerSettings);
  serializer.Serialize(writer, foo);

这将产生这个 JSON:

 {
     Date = "2019-02-26",
     CreationDate = "2019-02-26"
 }

由于 IsoDateTimeConverter

DateCreationDate 的序列化方式相同

我想做的是区分DateTimeDateTimeOffset

的序列化

我的目标是得到这个 JSON:

 {
     Date = "2019-02-26",
     CreationDate = "2019-02-26T12:03:00-03:00"
 }

我怎样才能做到这一点?

附加信息:

你可以试试这个

public class DateFormatConverter : IsoDateTimeConverter
{
    public DateFormatConverter(string format)
    {
        DateTimeFormat = format;
    }
}

为每个 Date 属性指定格式

public class Foo
{
    [JsonConverter(typeof(DateFormatConverter), "yyyy-MM-dd")]
    public DateTime Date { get; set; }

    [JsonConverter(typeof(DateFormatConverter), "yyyy-MM-ddTHH:mm:ssK")]
    public DateTimeOffset CreationDate { get; set; }
}

无需额外设置,您可以Serialize

Foo foo = new Foo();
foo.Date = DateTime.UtcNow;
foo.CreationDate = DateTime.UtcNow;

string isoJson = JsonConvert.SerializeObject(foo);

输出

{"Date":"2020-02-26","CreationDate":"2020-02-26T15:30:19-03:00"}