1

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
);
zhuber
  • 5,364
  • 3
  • 30
  • 63
  • 2
    It looks like you're just using default serialization, which is going to struggle when *deserializing* to immutable value types. It looks like you're probably using Json.NET, so use the `NodaTime.Serialization.JsonNet` library to perform appropriate serialization and deserialization. (This will make the stored data *much* more readable too...) – Jon Skeet Mar 30 '20 at 08:27
  • Exactly! Dunno why I thought that "whole object" serialization was correct, once I've added `JsonConvert.SerializeObject(r, NodaConverters.LocalTimeConverter)` from `NodaTime.Serialization.JsonNet`, it's serialized as string and correctly deserialized. Thanks @JonSkeet, will close the issue. – zhuber Mar 30 '20 at 08:39

1 Answers1

1

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"}]
zhuber
  • 5,364
  • 3
  • 30
  • 63