【问题标题】:How to tell ServiceStack not to drop nulls in my list?如何告诉 ServiceStack 不要在我的列表中删除空值?
【发布时间】:2014-10-30 02:00:11
【问题描述】:

我有这个问题,列表中的空日期时间没有被正确序列化/反序列化。

查看此示例代码:

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),它看起来像这样:

{"MyList":["2000-01-01T00:00:00.0000000Z",null,"2000-12-31T00:00:00.0000000Z"]}

我让我的 JsConfig 包含空值...那又是什么呢?

【问题讨论】:

    标签: c# json datetime servicestack


    【解决方案1】:

    这适用于最新版本的 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));
    }
    

    【讨论】:

    猜你喜欢
    • 2012-10-20
    • 2014-04-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-20
    相关资源
    最近更新 更多