简体   繁体   English

newtonsoft json序列化时间跨度格式

[英]newtonsoft json serialize timespan format

Is it possible to specify custom format for TimeSpan serialization? 是否可以为TimeSpan序列化指定自定义格式? Using Newtonsoft.Json . 使用Newtonsoft.Json

I would like to have serialized string in format HH:mm, so for example: 我想要格式化HH:mm的序列化字符串,例如:

TimeSpan.FromHours(5) -> // "+05:00" TimeSpan.FromHours(5) - > //“+05:00”

TimeSpan.FromHours(-5) -> // "-05:00" TimeSpan.FromHours(-5) - > //“ - 05:00”

Thanks! 谢谢!

As you can see in the source code , there is no way of changing the format using predefined setting (like for DateTime ). 正如您在源代码中看到的那样 ,无法使用预定义设置更改格式(例如DateTime )。

What you can do is write a new JsonConverter for TimeSpan and handle the formatting as you see fit. 您可以做的是为TimeSpan编写一个新的JsonConverter并根据需要处理格式。 Just be sure to use it by including it in JsonSerializerSettings.Converters or by modifying the default settings. 只需确保通过将其包含在JsonSerializerSettings.Converters或通过修改默认设置来使用它。

Here's a TimeSpan converter you can add to your project: 这是您可以添加到项目中的TimeSpan转换器:

using System;
using Newtonsoft.Json;

namespace JsonTools
{
    /// <summary>
    /// TimeSpans are not serialized consistently depending on what properties are present. So this 
    /// serializer will ensure the format is maintained no matter what.
    /// </summary>
    public class TimespanConverter : JsonConverter<TimeSpan>
    {
        /// <summary>
        /// Format: Days.Hours:Minutes:Seconds:Milliseconds
        /// </summary>
        public const string TimeSpanFormatString = @"d\.hh\:mm\:ss\:FFF";

        public override void WriteJson(JsonWriter writer, TimeSpan value, JsonSerializer serializer)
        {
            var timespanFormatted = $"{value.ToString(TimeSpanFormatString)}";
            writer.WriteValue(timespanFormatted);
        }

        public override TimeSpan ReadJson(JsonReader reader, Type objectType, TimeSpan existingValue, bool hasExistingValue, JsonSerializer serializer)
        {
            TimeSpan parsedTimeSpan;
            TimeSpan.TryParseExact((string)reader.Value, TimeSpanFormatString, null, out parsedTimeSpan);
            return parsedTimeSpan;
        }
    }
}

It can be used like this: 它可以像这样使用:

public class Schedule
{
    [JsonConverter(typeof(TimespanConverter))]
    [JsonProperty(TypeNameHandling = TypeNameHandling.All)]
    public TimeSpan Delay { get; set; }
}

Notes: 笔记:

  1. Reference for TimeSpan serialization formats TimeSpan序列化格式的参考

  2. I found that when generating a schema using Newtonsoft I had to include the TypeNameHandling attribute or the TimeSpan type name was not being serialized properly in the generated schema. 我发现在使用Newtonsoft生成模式时,我必须包含TypeNameHandling属性,或者TimeSpan类型名称未在生成的模式中正确序列化。 That isn't necessary for the purpose here, but I included it anyway. 这不是为了这个目的所必需的,但无论如何我都把它包括在内。

You can get a DateTime instance, and then add and subtract time from it like: 您可以获取DateTime实例,然后从中添加和减去时间,如:

System.DateTime timeNow = System.DateTime.Now;
DateTime futureDateTime = timeNow.Add(new TimeSpan(5, 0, 0));
DateTime prevDateTime = timeNow.Add(new TimeSpan(-5, 0, 0));

To specify the times that you need. 指定所需的时间。 Then to put them into your string format: 然后将它们放入您的字符串格式:

futureDateTime.ToString("hh:mm") // 12 hour clock

To deserialize the string value back into DateTime objects with a certain format, there's an example of specifying a DateTimeFormat and IsoDateTimeConverter in this post: Deserializing dates with dd/mm/yyyy format using Json.Net 要将字符串值反序列化为具有特定格式的DateTime对象,可以在此帖子中指定DateTimeFormat和IsoDateTimeConverter: 使用Json.Net以dd / mm / yyyy格式反序列化日期

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM