Poison.encode! error when preparing a body - (Poison.EncodeError) unable to encode value

I’m fetching some data from a mongodb database and I will use it to prepare a json body to send another HTTP request with HTTPoison so I’m using Poison as always to encode the body into JSON STRING, but there is a BSON ObjectId “_id” field in my body and I have this error :

data: %{
      "name" => "jack",
      "age" => 25,
       "_id" => #BSON.ObjectId<605200d8099f1c001f5f1d61>
}

Poison.encode!(data)

LOG :
** (exit) an exception was raised:
    ** (Poison.EncodeError) unable to encode value: <<216, 9, 159, 28, 0, 31, 95, 29, 97>>

Is there a solution ? thanks

Maybe relevant: JSON encoding · Issue #46 · elixir-mongo/mongodb · GitHub

Yes, but I didn’t find the solution

More specifically: JSON encoding · Issue #46 · elixir-mongo/mongodb · GitHub

This is only a guess, but the BSON.ObjectId can’t be encoded as is, and needs special treatment; you have to tell Poison to encode BSON.ObjectId’s, I think.

Exactly, but I didn’t figure out the treatment

Have you tried making a module under the lib directory as mentioned in that post? Try putting that code in a module named something like BSONObjectId in a file named something like lib/bson_object_id.ex. Are you stuck at the consolidated protocol error also mentioned in that post?

It sounds like you found this GitHub issue, but I cannot guess how much you’ve read, or what you’ve tried, or what new errors you’ve seen.

fixed by adding this in my application.ex in the lib folder :

  defimpl Poison.Encoder, for: BSON.ObjectId do
    def encode(id, options) do
      BSON.ObjectId.encode!(id) |> Poison.Encoder.encode(options)
    end
  end