Zoltán
Zoltán

Reputation: 22156

Elixir Phoenix Parse JSON as Struct

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

Upvotes: 1

Views: 643

Answers (1)

Daniel
Daniel

Reputation: 2554

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.

Upvotes: 2

Related Questions