Elixir Jason encode struct with tuple

白昼怎懂夜的黑 提交于 2020-12-30 06:42:49

问题


I have a struct which already has @derive Jason.Encoder but some fields in that struct are tuples, and for this reason cannot encode the struct, how can I fix that :/

UPDATE

I have used the approach that mentioned below with implementing a protocol. One important thing to note about this approach is that it will change the encoding for the whole project, just be careful with that !


回答1:


Have a look at the documentation for how you need to implement the encode/2 function: https://hexdocs.pm/jason/Jason.Encoder.html

As part of your implementation, you need to decide how you want to encode a tuple since it doesn't have an analog in JSON. An array is probably the easiest option, so you could do mytuple |> Tuple.to_list




回答2:


If you do need to encode tuples as a list type, this works:

defmodule TupleEncoder do
  alias Jason.Encoder

  defimpl Encoder, for: Tuple do
    def encode(data, options) when is_tuple(data) do
      data
      |> Tuple.to_list()
      |> Encoder.List.encode(options)
    end
  end
end

You should be able to use a similar pattern to convert it to another primitive structure as needed.



来源:https://stackoverflow.com/questions/56164792/elixir-jason-encode-struct-with-tuple

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!