5

I'm having trouble serialising and de-serialising NodaTime's LocalTime through a WebAPI.

Class definition

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

Try to serialize the output

// 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);

I want to time format formatted to a ISO like standard e.g. 12:34:53, but instead it de-serialisers to the following with local time represented as ticks;

{ "ExampleLocalTime": { "ticks": 553800000000 } }

What do I need to add to avoid Ticks when de-serialising and serialising?

Matt Johnson-Pint
  • 230,703
  • 74
  • 448
  • 575
wonea
  • 4,783
  • 17
  • 86
  • 139

1 Answers1

5

Noda Time has an additional NuGet package available for JSON.Net serialization.

PM>  Install-Package NodaTime.Serialization.JsonNet

To use it, simply invoke its configuration extension method:

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

You can read more about it in the Noda Time user guide (about half-way down the page).

Matt Johnson-Pint
  • 230,703
  • 74
  • 448
  • 575