Suppose I'm building an API that is versioned (as an example let's use a user object):
%User{
id: "b2507407-891b-486e-aaf8-ba262c16d618"
first_name: "John",
last_name: "Doe",
email: "[email protected]"
}
My initial thought was to have multiple encoders for different versions of the API I would run different Jason encoders:
defimpl Jason.EncoderV1, for: __MODULE__ do
def encode(user, opts) do
Jason.Encode.map(%{name: "#{user.first_name} #{user.last_name}"}, opts)
end
end
defimpl Jason.EncoderV2, for: __MODULE__ do
def encode(user, opts) do
Jason.Encode.map(%{first_name: first_name, last_name: last_name}, opts)
end
end
I did not see any reference in the Jason docs that would allow this.
You should somehow tell
Jason
what version do you want to use.Jason.Encoder.encode/2
has the second parameter for this.And call it like
Jason.encode!(any, version: :v2)
.Sidenote:
defimpl
expects the module that defines a protocol as a first parameter, one cannot pass whatever, like inexistingJason.EncoderV2
there.