从elixir ecto协会创建json

ido*_*obn 7 json elixir ecto phoenix-framework

我想从凤凰城的一个ecto协会生成JSON.

这是我的协会:

defmodule Blog.Post do
  use Ecto.Model

  schema "posts" do
    field :title, :string
    field :body, :string
    has_many :comments, Blog.Comment
  end
end
Run Code Online (Sandbox Code Playgroud)

和:

defmodule Blog.Comment do
  use Ecto.Model

  schema "comments" do
    field :content, :string
    belongs_to :post, Blog.Post
  end
end
Run Code Online (Sandbox Code Playgroud)

当我生成没有关联的json时,结果如下:

[%Blog.Post{body: "this is the very first post ever!", id: 1,title: "first post"},
 %Blog.Post{body: "Hello nimrod!!!!", id: 12, title: "hi Nimrod"},
 %Blog.Post{body: "editing the body!!!!", id: 6, title: "hello(edit)"}]
Run Code Online (Sandbox Code Playgroud)

而json看起来像这样

{"posts": [
    {
        "title": "first post",
        "id": 1,
        "body": "this is the very first post ever!"
    },
    {
        "title": "hi Nimrod",
        "id": 12,
        "body": "Hello nimrod!!!!"
    },
    {
        "title": "hello(edit)",
        "id": 6,
        "body": "editing the body!!!!"
    }
]}
Run Code Online (Sandbox Code Playgroud)

但结果就是结果

[%Blog.Post{body: "this is the very first post ever!",
 comments: {Ecto.Associations.HasMany.Proxy,
 #Ecto.Associations.HasMany<[name: :comments, target: Blog.Post,
 associated: Blog.Comment, references: :id, foreign_key: :post_id]>}, id: 1,
 title: "first post"},
 %Blog.Post{body: "Hello nimrod!!!!",
 comments: {Ecto.Associations.HasMany.Proxy,
 #Ecto.Associations.HasMany<[name: :comments, target: Blog.Post,
 associated: Blog.Comment, references: :id, foreign_key: :post_id]>}, id: 12,
 title: "hi Nimrod"},
 %Blog.Post{body: "editing the body!!!!",
 comments: {Ecto.Associations.HasMany.Proxy,
 #Ecto.Associations.HasMany<[name: :comments, target: Blog.Post,
 associated: Blog.Comment, references: :id, foreign_key: :post_id]>}, id: 6,
 title: "hello(edit)"}]
Run Code Online (Sandbox Code Playgroud)

使用上面的输出我无法创建正确的json输出.我想让json看起来像这样

{"posts": [
     {
        "title": "the title",
        "id": 1,
        "body": "the body",
        "comments": [{"content": "a comment"}, {"content": "another comment"}]
     }
     ...
]}
Run Code Online (Sandbox Code Playgroud)

任何帮助,将不胜感激.

Jos*_*lim 6

哎呀,目前还没有简单的解决方案.我会尝试类似的东西:

defimpl Poison.Encoder, for: Tuple do
  def encode(proxy, options) do
    Poison.Encoder.List.to_json(proxy.all, options)
  end
end
Run Code Online (Sandbox Code Playgroud)

我们基本上为接收上面的代理和编码所有项目的元组实现编码器.我们需要为此讨论更好的解决方案.