Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
613 views
in Technique[技术] by (71.8m points)

phoenix framework - Encoding a Ecto Model to JSON in elixir

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

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 and the fix: https://coderwall.com/p/fhsehq/fix-encoding-issue-with-ecto-and-poison

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

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
question from:https://stackoverflow.com/questions/32549712/encoding-a-ecto-model-to-json-in-elixir

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...