返回列表给出 (Poison.EncodeError) unable to encode value
returning a list gives (Poison.EncodeError) unable to encode value
IO.puts(inspect( contacts )) 给出:
[%HelloTable.Contact{__meta__: #Ecto.Schema.Metadata<:loaded>,
id: 37,
inserted_at: #Ecto.DateTime<2015-10-22T12:50:43Z>,
name: "Gumbo", phone: "(801) 555-55555",
updated_at: #Ecto.DateTime<2015-10-22T12:50:43Z>}]
视图看起来像:
defmodule HelloTable.ContactView do
use HelloTable.Web, :view
def render("index.json", %{contacts: contacts}) do
IO.puts(inspect( contacts ))
contacts
end
end
当我尝试渲染这个视图时,我得到:
** (Poison.EncodeError) unable to encode value: {nil, "contacts"}
您需要为 HelloTable.Contact
实施 Poison.Encoder
协议,如 or return a map from the render function using render_many/4 中所述:
defmodule HelloTable.ContactView do
use HelloTable.Web, :view
def render("index.json", %{contacts: contacts}) do
render_many(contacts, __MODULE__, "contact.json")
end
def render("contact.json", %{contact: contact}) do
%{
id: contact.id,
name: contact.name,
phone_number: contact.phone
}
end
end
以上是 JSON 在 Phoenix JSON generators 中的处理方式。
.
中描述了使用更高版本毒药的另一个可能更清洁的解决方案
将这行代码添加到您的模型中:
@derive {Poison.Encoder, only: [:name, :phone]}
(如果您希望 JSON 中包含该字段,您还可以包括:updated_at)
IO.puts(inspect( contacts )) 给出:
[%HelloTable.Contact{__meta__: #Ecto.Schema.Metadata<:loaded>,
id: 37,
inserted_at: #Ecto.DateTime<2015-10-22T12:50:43Z>,
name: "Gumbo", phone: "(801) 555-55555",
updated_at: #Ecto.DateTime<2015-10-22T12:50:43Z>}]
视图看起来像:
defmodule HelloTable.ContactView do
use HelloTable.Web, :view
def render("index.json", %{contacts: contacts}) do
IO.puts(inspect( contacts ))
contacts
end
end
当我尝试渲染这个视图时,我得到:
** (Poison.EncodeError) unable to encode value: {nil, "contacts"}
您需要为 HelloTable.Contact
实施 Poison.Encoder
协议,如
defmodule HelloTable.ContactView do
use HelloTable.Web, :view
def render("index.json", %{contacts: contacts}) do
render_many(contacts, __MODULE__, "contact.json")
end
def render("contact.json", %{contact: contact}) do
%{
id: contact.id,
name: contact.name,
phone_number: contact.phone
}
end
end
以上是 JSON 在 Phoenix JSON generators 中的处理方式。
将这行代码添加到您的模型中:
@derive {Poison.Encoder, only: [:name, :phone]}
(如果您希望 JSON 中包含该字段,您还可以包括:updated_at)