【问题标题】:Proper serialization of LocalTime through WebAPI通过 WebAPI 正确序列化 LocalTime
【发布时间】:2014-06-30 01:19:15
【问题描述】:

我在通过 WebAPI 序列化和反序列化 NodaTime 的 LocalTime 时遇到问题。

类定义

public class ExampleClass
{
    public LocalTime ExampleLocalTime { get; set; }
}

尝试序列化输出

// create example object
var exampleclass = new ExampleClass() 
{ 
    ExampleLocalTime = new LocalTime(DateTime.Now.Hour, DateTime.Now.Minute) 
};
// serialise output
var jsonsettings = new JsonSerializerSettings()
{
    DateParseHandling = DateParseHandling.None,
    NullValueHandling = NullValueHandling.Ignore
};
jsonsettings.Converters.Add(new IsoDateTimeConverter());
string exampleoutput = JsonConvert.SerializeObject(exampleclass, Formatting.Indented, jsonsettings);

我想将时间格式格式化为 ISO 标准,例如12:34:53,而是将本地时间反序列化为以下内容;

{ “示例本地时间”:{ “滴答声”:553800000000 } }

在反序列化和序列化时我需要添加什么以避免Ticks

【问题讨论】:

    标签: c# asp.net-web-api json.net nodatime


    【解决方案1】:

    Noda Time 有一个额外的 NuGet 包可用于 JSON.Net 序列化。

    PM>  Install-Package NodaTime.Serialization.JsonNet
    

    要使用它,只需调用它的配置扩展方法:

    var jsonsettings = new JsonSerializerSettings()
    jsonsettings.ConfigureForNodaTime();
    

    您可以阅读更多关于它的信息in the Noda Time user guide(大约在页面的一半处)。

    【讨论】:

      猜你喜欢
      • 2017-05-26
      • 2016-07-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-11
      • 1970-01-01
      • 1970-01-01
      • 2014-08-16
      相关资源
      最近更新 更多