gpt4 book ai didi

elixir - 返回列表给出(Poison.EncodeError)无法编码值

转载 作者:行者123 更新时间:2023-12-02 09:02:16 25 4
gpt4 key购买 nike

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>}]

View 看起来像:

defmodule HelloTable.ContactView do
use HelloTable.Web, :view

def render("index.json", %{contacts: contacts}) do
IO.puts(inspect( contacts ))
contacts
end

end

当我尝试渲染此 View 时,我得到:

** (Poison.EncodeError) unable to encode value: {nil, "contacts"}

最佳答案

您需要为 HelloTable.Contact 实现 Poison.Encoder 协议(protocol),如 Encoding a Ecto Model to JSON in elixir 中所述。或使用 render_many/4 从渲染函数返回 map :

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

以上是 Phoenix JSON generators 中 JSON 的处理方式.

关于elixir - 返回列表给出(Poison.EncodeError)无法编码值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33281803/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com