Reputation: 22156
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