zhuber
zhuber

Reputation: 5524

NodaTime database json serialization

I'm saving list of schedules in my jsonb column in postgres database and I'm having problems with LocalDate NodaTime type.

Here is my object that is being serialized (actually List<Schedule> is serialized and stored in database)

public class Schedule
{
    public LocalTime? Start { get; set; }
    public LocalTime? End { get; set; }
}

This is what's get stored in the database

[
    {
        "End": {
            "Hour": 10,
            "Minute": 0,
            "Second": 0,
            "TickOfDay": 360000000000,
            "Millisecond": 0,
            "TickOfSecond": 0,
            "NanosecondOfDay": 36000000000000,
            "ClockHourOfHalfDay": 10,
            "NanosecondOfSecond": 0
        },
        "Start": {
            "Hour": 8,
            "Minute": 0,
            "Second": 0,
            "TickOfDay": 288000000000,
            "Millisecond": 0,
            "TickOfSecond": 0,
            "NanosecondOfDay": 28800000000000,
            "ClockHourOfHalfDay": 8,
            "NanosecondOfSecond": 0
        }
    }
]

Which seems pretty fine to me, but the problem is when I'm fetching the data from database my LocalDate's are '00:00:00'.

Serialization/Deserialization is done using

var converter = new ValueConverter<T, string>
(
    v => JsonConvert.SerializeObject(v),
    v => JsonConvert.DeserializeObject<T>(v) ?? null
);

Upvotes: 1

Views: 282

Answers (1)

zhuber
zhuber

Reputation: 5524

I've added the NodaTime.Serialization.JsonNet as suggested in the comments and changed the converter for Entity Framework to:

var converter = new ValueConverter<T, string>
(
    v => JsonConvert.SerializeObject(v, NodaConverters.LocalTimeConverter),
    v => JsonConvert.DeserializeObject<T>(v, NodaConverters.LocalTimeConverter) ?? null
);

This now correctly serializes to string and successfully deserializes.

[{"End": "10:00:00", "Start": "09:00:00"}]

Upvotes: 1

Related Questions