我遇到这个问题,列表中的空日期时间没有正确序列化/反序列化。
请参阅此示例代码:
internal class WrapperNullableDateTimeList
{
public List<DateTime?> MyList { get; set; }
}
public void T14_Should_skip_output_nullable_datetime_in_list_TODO_THIS_IS_WRONG()
{
WrapperNullableDateTimeList input = new WrapperNullableDateTimeList();
input.MyList = new List<DateTime?>()
{
new DateTime(2000, 01, 01, 0, 0, 0, 0, DateTimeKind.Utc),
null,
new DateTime(2000, 12, 31, 0, 0, 0, 0, DateTimeKind.Utc),
};
JsConfig.IncludeNullValues = true;
var serializer = new JsonSerializer<WrapperNullableDateTimeList>();
string serializedInput = serializer.SerializeToString(input);
WrapperNullableDateTimeList output = serializer.DeserializeFromString(serializedInput);
output.MyList.Count.Should().Be(3); // Fails here! The 'null' DateTime in the list is dropped
}
有什么想法吗? 顺便说一下,我打印了serializedInput(json),它看起来像这样:
{&#34; MYLIST&#34;:[&#34; 2000-01-01T00:00:00.0000000Z&#34;,NULL,&#34; 2000-12-31T00:00:00.0000000Z&#34 ]}
我让我的JsConfig包含空值...所以给出了什么?
答案 0 :(得分:2)
这适用于最新版本的ServiceStack:
using (JsConfig.With(new Config { includeNullValues = true }))
{
var dto = new WrapperNullableDateTimeList
{
MyList = new List<DateTime?>
{
new DateTime(2000, 01, 01, 0, 0, 0, 0, DateTimeKind.Utc),
null,
new DateTime(2000, 12, 31, 0, 0, 0, 0, DateTimeKind.Utc),
}
};
var json = dto.ToJson();
json.Print();
Assert.That(json, Is.EqualTo(
@"{""MyList"":[""\/Date(946684800000)\/"",null,""\/Date(978220800000)\/""]}"));
var fromJson = json.FromJson<WrapperNullableDateTimeList>();
Assert.That(fromJson.MyList.Count, Is.EqualTo(dto.MyList.Count));
}