Newtonsoft JSON如何动态更改日期格式?

时间:2014-06-11 14:05:56

标签: json.net

我正在使用Newtonsoft JSON Serializer,它非常棒且超快,但我想用它做更多的事情。我不确定这是可能的,因为我所做的所有搜索都没有结果。我想要的是能够截断空闲时间,所以当它显示2014-01-01 00:00:00.000时我最后只需要2014-01-01,所以基本上切掉它们全部为零时的整个时间。现在我使用这段代码:

DataTable dt = loadData();

// encode the string with Newton JSON.Net 
string output = JsonConvert.SerializeObject(dt,
    new JsonSerializerSettings
    {
        ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
        Formatting = Newtonsoft.Json.Formatting.None,
        DateFormatString = "yyyy-MM-dd HH:mm:ss"
    });

有没有办法在没有时间的情况下(只有当它们都是零)格式化这些日期而不影响性能?

1 个答案:

答案 0 :(得分:1)

您可以使用自定义JsonConverter执行此操作:

class CustomDateConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return (objectType == typeof(DateTime));
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        DateTime date = (DateTime)value;
        string format = "yyyy-MM-dd HH:mm:ss";
        if (date.Hour == 0 && 
            date.Minute == 0 && 
            date.Second == 0 && 
            date.Millisecond == 0)
        {
            format = "yyyy-MM-dd";
        }
        writer.WriteValue(date.ToString(format));
    }

    public override bool CanRead
    {
        get { return false; }
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }
}

演示:

class Program
{
    static void Main(string[] args)
    {
        List<DateTime> dates = new List<DateTime>
        {
            DateTime.Now,
            DateTime.Today
        };

        JsonSerializerSettings settings = new JsonSerializerSettings
        {
            ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
            Formatting = Newtonsoft.Json.Formatting.None,
            Converters = new List<JsonConverter> { new CustomDateConverter() }
        };

        string json = JsonConvert.SerializeObject(dates, settings);

        Console.WriteLine(json);
    }
}

输出:

["2014-06-11 11:56:28","2014-06-11"]