Deserializing struct's from string to DateTime

I have a struct containing some DateTime fields. When I put it to Redis, it gets serialized as json (using Jason lib). So when it gets deserialized the datetime fields come back as strings.

How to restore the data to its original data type? Is there a Plug or Protocol to implement to tell Jason to decode those fields as DateTime?

Jason doesn’t support extra decoding functionality the same way that it supports custom encoding via its Elixir Protocol. You’re better off just using JSON decoding first and then parse the date strings.

…or you can store your Elixir data structures in Redis verbatim with :erlang.term_to_binary function for encoding and then :erlang.binary_to_term for decoding.

If you have ecto around you can use Ecto.Type or Repo.load to transform data back to their higher level types.

1 Like