【发布时间】:2019-12-13 18:28:17
【问题描述】:
基于this answer,我知道如何使用Poison.decode/2将JSON解析为结构:
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{}})
但是我如何告诉菲尼克斯也这样做呢?如果我告诉它我的端点接受 JSON,它会自动将其解析为地图:
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
【问题讨论】: