在elixir中将Ecto模型编码为JSON [英] Encoding a Ecto Model to JSON in elixir

查看:77
本文介绍了在elixir中将Ecto模型编码为JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读以下教程,以期了解around剂和凤凰:

I am going over the following tutorial in an attempt to get my head around elixir and phoenix:

https://thoughtbot.com/blog/testing-a -phoenix-elixir-json-api

我在测试中遇到了一个问题,主要是使用Poison.encode!在联系人模型上.我收到以下错误:

I am running into an issue with the test, mainly using Poison.encode! on the Contact model. I get the following error:

unable to encode value: {nil, "contacts"}

这导致我遇到以下问题:

This led me to the following issue:

https://github.com/elixir-lang/ecto/issues/840 和解决方法: https://coderwall.com/p/fhsehq/修正带有外来毒素的编码问题

我已将博客文章中的代码添加到lib/poison_encoder.ex中,但是现在出现以下错误:

I have added the code from the blog article into lib/poison_encoder.ex, but I now get the following error:

no function clause matching in Poison.Encoder.Any.encode/2

我在lib/poison_encoder.ex中拥有的代码:

The code I have in lib/poison_encoder.ex:

defimpl Poison.Encoder, for: Any do
  def encode(%{__struct__: _} = struct, options) do
    map = struct
          |> Map.from_struct
          |> sanitize_map
    Poison.Encoder.Map.encode(map, options)
  end

  defp sanitize_map(map) do
    Map.drop(map, [:__meta__, :__struct__])
  end
end

推荐答案

更新为Poison 1.5.有了它,您可以在模型中声明:

Update to Poison 1.5. With it you can declare in your models:

@derive {Poison.Encoder, only: [:foo, :bar, :baz]}
schema "your schema" do
  field :foo
  field :bar
  field :baz
end

它将更快,更安全,更清洁.

It is going to be faster, safer and cleaner.

这篇关于在elixir中将Ecto模型编码为JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆