Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proper serialization of LocalTime through WebAPI

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?

like image 237
wonea Avatar asked Jun 29 '14 14:06

wonea


Video Answer


1 Answers

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).

like image 78
Matt Johnson-Pint Avatar answered Oct 11 '22 17:10

Matt Johnson-Pint