【问题标题】:returning a list gives (Poison.EncodeError) unable to encode value返回列表会导致 (Poison.EncodeError) 无法编码值
【发布时间】:2016-01-21 18:40:03
【问题描述】:

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

【问题讨论】:

    标签: elixir phoenix-framework ecto


    【解决方案1】:

    您需要为HelloTable.Contact 实现Poison.Encoder 协议,如Encoding a Ecto Model to JSON in elixir 中所述,或者使用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
    

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

    【讨论】:

    • 谢谢,它可以工作,只是在contact.name之后缺少逗号。
    • 这似乎不起作用。此外,您在第一个 def 中缺少 %{data: render_many...}%
    【解决方案2】:

    this response to a similar question 中描述了另一种使用更高版本毒药的可能更清洁的解决方案。

    将这行代码添加到您的模型中:

    @derive {Poison.Encoder, only: [:name, :phone]}
    

    (如果您希望 JSON 中包含该字段,您还可以包含 :updated_at)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-02-01
      • 1970-01-01
      • 2022-01-08
      • 2015-06-02
      • 2021-09-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多