如何使用JsonConverter属性格式化日期列表 [英] How to format a list of dates using JsonConverter attribute
问题描述
我正在使用WebApi 2服务,该服务以JSON格式返回数据.我为DateTimes使用两种格式,日期:"2017-01-31"和日期时间:"2017-01-31T12:00:00.000Z".日期时间格式使用最多,因此我将其设置为global.asax中的默认格式:
I'm working on a WebApi 2 service that returns data in JSON format. I use two formats for DateTimes, date: "2017-01-31" and datetime: "2017-01-31T12:00:00.000Z". The datetime format is used the most so I've set this as the default in the global.asax:
config.Formatters.JsonFormatter.SerializerSettings.Converters.Add(new IsoDateTimeConverter() { DateTimeFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fff'Z'" });
然后在需要格式化为日期的那些DateTime字段上使用一个自定义IsoDateTimeConverter的JsonConverter属性:
And I use a JsonConverter attribute using a custom IsoDateTimeConverter on those DateTime fields that need to be formatted as date:
public class Foo
{
[JsonConverter(typeof(OnlyDateConverter))]
public DateTime Bar { get; set; }
}
public class OnlyDateConverter : IsoDateTimeConverter
{
public OnlyDateConverter()
{
DateTimeFormat = "yyyy-MM-dd";
}
}
到目前为止,一切都很好,这就像一种魅力.
So far all is fine, this works like a charm.
但这是问题所在: 对于某些对象,我有一个DateTime对象列表,需要将其格式化为日期.但是JSON转换器似乎不支持在列表上使用JsonConverter属性.
But here's the problem: For some objects I have a list of DateTime objects that need to be formatted as date. But the JSON converter seems to not support using a JsonConverter attribute on a list.
public class Foo
{
[JsonConverter(typeof(OnlyDateConverter))] // This works
public DateTime Bar { get; set; }
[JsonConverter(typeof(OnlyDateConverter))] // This does not work!
public List<DateTime> Bars { get; set; }
}
这将导致以下错误:转换日期时出现意外值.预期的DateTime或DateTimeOffset,获得了System.Collections.Generic.List`1 [System.DateTime].
This results in the following error: Unexpected value when converting date. Expected DateTime or DateTimeOffset, got System.Collections.Generic.List`1[System.DateTime].
很清楚,您不能在日期列表上使用[JsonConverter(typeof(OnlyDateConverter))].但是,如何将日期时间列表格式化为日期呢?
Pretty clear, you can't use [JsonConverter(typeof(OnlyDateConverter))] on a list of dates. But then how do I format a list of DateTime as date?
我一直在寻找解决方案,但是除了创建一个仅包含一个带有属性的DateTime属性的类外,似乎找不到其他任何东西.但这对我来说似乎不正确.
I've been searching for a solution but can't seem to find anything other than creating a class that consists of just one DateTime property with the attribute. But that just doesn't seem right to me.
肯定有一种方法可以在DateTimes列表上使用JsonConverter属性吗?我在这里想念什么?
Surely there must be a way to use the JsonConverter attribute on a list of DateTimes? What am I missing here?
推荐答案
使用[JsonProperty(ItemConverterType = typeof(MyDateTimeConverter))]
use [JsonProperty(ItemConverterType = typeof(MyDateTimeConverter))]
这篇关于如何使用JsonConverter属性格式化日期列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!