问题
I have a DateTimeOffset object of "05/06/2014 05:54:00 PM -04:00".
When serializing using Json.NET and ISO setting, I get "2014-05-06T17:54:00-04:00".
What I would like to have is the UTC/Zulu version of that string "2014-05-06T21:54:00Z".
However, I could not find any serializer setting to achieve this. I know for DateTime serialization, I can set DateTimeZoneHandling = DateTimeZoneHandling.Utc to have the Zulu format. However, there isn't such setting option for DateTimeOffset. Am I missing something? Or do I have to create a custom override for this?
回答1:
Try using the IsoDateTimeConverter
that comes with Json.Net:
var date = new DateTime(2014, 5, 6, 17, 24, 55, DateTimeKind.Local);
var obj = new { date = new DateTimeOffset(date) };
JsonSerializerSettings settings = new JsonSerializerSettings();
settings.Converters.Add(new IsoDateTimeConverter
{
DateTimeFormat = "yyyy-MM-ddTHH:mm:ssZ",
DateTimeStyles = DateTimeStyles.AdjustToUniversal
});
string json = JsonConvert.SerializeObject(obj, settings);
Console.WriteLine(json);
Output:
{"date":"2014-05-06T22:24:55Z"}
回答2:
You can write a custom converter like this:
class UtcDateTimeOffsetConverter : Newtonsoft.Json.Converters.IsoDateTimeConverter
{
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
if (value is DateTimeOffset)
{
var date = (DateTimeOffset)value;
value = date.UtcDateTime;
}
base.WriteJson(writer, value, serializer);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
object value = base.ReadJson(reader, objectType, existingValue, serializer);
if (value is DateTimeOffset)
{
var date = (DateTimeOffset)value;
value = date.ToLocalTime();
}
return value;
}
}
And apply it on the property you want using the JsonConverter
attribute:
[JsonConverter(typeof(UtcDateTimeOffsetConverter))]
public DateTimeOffset Date { get; set; }
来源:https://stackoverflow.com/questions/23505294/is-it-possible-to-serialize-datetimeoffset-to-zulu-time-string-with-json-net