won*_*nea 5 c# json.net asp.net-web-api nodatime
我无法通过WebAPI对NodaTime的LocalTime进行序列化和反序列化.
类定义
public class ExampleClass
{
public LocalTime ExampleLocalTime { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
尝试序列化输出
// 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);
Run Code Online (Sandbox Code Playgroud)
我希望格式化为ISO格式的时间格式,例如12:34:53,而是将其解串行化为以下,本地时间表示为刻度;
{"ExampleLocalTime":{"ticks":553800000000}}
在反序列化和序列化时,我需要添加什么来避免Ticks?
Noda Time有一个额外的NuGet包可用于JSON.Net序列化.
PM> Install-Package NodaTime.Serialization.JsonNet
Run Code Online (Sandbox Code Playgroud)
要使用它,只需调用其配置扩展方法:
var jsonsettings = new JsonSerializerSettings()
jsonsettings.ConfigureForNodaTime();
Run Code Online (Sandbox Code Playgroud)
您可以在Noda Time用户指南中了解更多相关信息(大约在页面的一半).