Newtonsoft.Json序列化是否支持仅年份日期字段?
根据 ISO 8601 json日期字段可以包含部分数据,例如"YYYY"
仅用于年份,或"YYYY-MM"
仅用于年份-月份.
According to ISO 8601 json date fields can contain partial data, e.g. "YYYY"
for year-only or "YYYY-MM"
for year-month-only.
但是,以下代码使用 Json.NET解串器应该支持它,并引发格式错误:
But, the following code, using Json.NET deserializer that's supposed to support it, throws a format error:
class PartialDateContainter
{
public DateTime MyPartialDate { get; set; }
}
[Test]
public void JustCheckJsonDates()
{
var serializationSettings =
new JsonSerializerSettings
{
DateFormatHandling = DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = DateTimeZoneHandling.Utc,
NullValueHandling = NullValueHandling.Ignore,
ReferenceLoopHandling = ReferenceLoopHandling.Serialize,
ContractResolver = new ReadOnlyJsonContractResolver(),
Converters = new List<JsonConverter>
{
new Iso8601TimeSpanConverter(),
new IsoDateTimeConverter()
}
};
var ser = JsonSerializer.Create(serializationSettings);
var json = "{ \"MyPartialDate\": \"2005\" }";
var shus = ser.Deserialize<PartialDateContainter>(new JsonTextReader(new StringReader(json)));
Assert.True(true);
}
我想念什么吗?
Newtonsoft.Json序列化是否支持仅年份日期字段?
Does Newtonsoft.Json Serialization Support Year-Only Date Fields?
默认情况下不是.
但是它足够灵活,可以配置为仅支持年份日期字段.
But it is flexible enough that is can be configured to support year only date fields.
在此处引用Json.Net文档在JSON中序列化日期
Referencing Json.Net documentation here Serializing Dates in JSON
如果您的日期不符合ISO 8601标准,则
DateFormatString
设置可用于自定义日期格式 使用.NET的自定义日期和时间 格式语法.
If your dates don't follow the ISO 8601 standard, then the
DateFormatString
setting can be used to customize the format of date strings that are read and written using .NET's custom date and time format syntax.
以下简化示例有效
[TestClass]
public class JsonNetDateSerializationTests {
[TestMethod]
public void JustCheckJsonDates() {
//Arrange
var settings =
new JsonSerializerSettings {
DateFormatString = "yyyy", //<-- for year only dates. all others should parse fine
};
var json = "{ \"YearOnly\": \"2017\", \"YearMonth\": \"2017-04\", \"YearMonthDay\": \"2017-04-02\" }";
var expected = 2017;
//Act
var actual = JsonConvert.DeserializeObject<PartialDateContainter>(json, settings);
//Assert
Assert.IsNotNull(actual);
Assert.AreEqual(expected, actual.YearOnly.Year);
Assert.AreEqual(expected, actual.YearMonth.Year);
Assert.AreEqual(expected, actual.YearMonthDay.Year);
}
class PartialDateContainter {
public DateTime YearOnly { get; set; }
public DateTime YearMonth { get; set; }
public DateTime YearMonthDay { get; set; }
}
}