1

Based on this answer, I know how to parse JSON to a struct using Poison.decode/2:

defmodule User do
  @derive [Poison.Encoder]
  defstruct [:address]
end

defmodule Address do
  @derive [Poison.Encoder]
  defstruct [:street]
end

Poison.decode(response, as: %User{address: %Address{}})

But how do I tell Phoenix to do the same? If I tell it that my endpoint accepts JSON, it will just automatically parse it to a map:

defmodule MyAppWeb.Router do
  use MyAppWeb, :router

  pipeline :api do
    plug :accepts, ["json"]
  end

  scope "/api/v1", MyAppWeb do
    pipe_through :api

    put "/endpoint", MyController, :put
  end
end

defmodule MyController do
  def put(conn, %{"_json" => map}) do
    # Here, `map` is already parsed as a map. How can I tell Phoenix to
    # parse it as a struct I choose like I can tell `Poison` to do so?
  end
end

1 Answer 1

2

In your endpoint.ex you should have parsers plug:

 plug Plug.Parsers,
    parsers: [:urlencoded, :multipart, :json],
    pass: ["*/*"],
    json_decoder: Poison

Remove the json atom, that should disable the json parser.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.