【问题标题】:Jason encode binary to UUID in ElixirJason 在 Elixir 中将二进制编码为 UUID
【发布时间】:2021-01-08 00:15:03
【问题描述】:

我正在尝试一种干净的方法来覆盖二进制的JasonEncoder,这将允许我从二进制中提取 UUID。这是我理论上想做的事情:

defimpl Jason.Encoder, for: BitString do
  def encode(binary, opts) when is_binary(binary) do
    with false <- String.valid?(binary),
    {:ok, uid} <- Ecto.UUID.cast(binary) do
      uid
    else
    _ -> Jason.Encode.string(binary, opts)
    end
  end

  def encode(bitstring, _opts) do
    raise Protocol.UndefinedError,
      protocol: @protocol,
      value: bitstring,
      description: "cannot encode a bitstring to JSON"
  end
end

我正在考虑this stackoverflow 示例的思路,但我认为这里的问题是不能覆盖像 BitString 这样的本机类型。

【问题讨论】:

    标签: elixir uuid elixir-jason


    【解决方案1】:

    与其尝试全局覆盖BitString 的协议,不如将UUID 包装在它自己的结构中,并为该结构实现Jason.Encoder 协议:

    defmodule JsonUUID do
      defstruct [:uuid]
    
      defimpl Jason.Encoder do
        def encode(%JsonUUID{uuid: uuid}, opts) when is_binary(uuid) do
          uuid
          |> Ecto.UUID.cast!()
          |> Jason.Encode.string(opts)
        end
      end
    end
    

    测试:

    Jason.encode!(%JsonUUID{uuid: Ecto.UUID.bingenerate()})
    => "\"8cbf3df9-8408-4ce3-ac44-980a0f7dc19b\""
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-08-29
      • 1970-01-01
      • 1970-01-01
      • 2018-10-26
      • 2011-11-18
      • 2019-06-23
      • 2014-11-06
      • 1970-01-01
      相关资源
      最近更新 更多