[英]Limit fields of JSON response
我正在使用PhoenixFramework和库Poison 。 目前,我正在研究REST API。 现在,我需要以两种不同的方式对模型Book
进行编码。
GET /books
) GET /book/1
) GET /books
{
"books": [
{
"id": 1,
"name": "Book one"
},
{
"id": 2,
"name": "Book two"
},
// ...
]
}
GET /books/1
{
"book": {
"id": 1,
"name": "Book one",
"description": "This is book one.",
"author": "Max Mustermann",
// ...
}
}
Book
编码器
defimpl Poison.Encoder, for: MyProject.Book do
@attributes [:id, :name, :description, :author]
def encode(project, _options) do
project
|> Map.take(@attributes)
|> Poison.encode!
end
end
片段控制器
def index(conn, _params) do
books = Repo.all(Book)
json(conn, %{books: books})
end
如何限制字段? 我搜索诸如:only
或:exclude
类的选项。 有没有人遇到过这个问题?
感谢帮助!
您可以使用render_many / 4和render_one / 4 :
defmodule MyApp.BookView do
def render("index.json", %{books: books}) do
render_many(books, __MODULE__, "book.json")
end
def render("show.json", %{book: book}) do
render_one(book, __MODULE__, "full_book.json")
end
def render("book.json", %{book: book}) do
%{
id: book.id,
name: book.name
}
end
def render("full_book.json", %{book: book}) do
%{
id: book.id,
name: book.name,
description: description,
author: book.author
...
}
end
end
请注意,assign中的名称(render的第二个参数)由模块确定。 有关使用其他名称的示例,请参见Phoenix框架中的呈现多对多关系JSON 。
然后,您可以使用以下命令从控制器中调用此命令:
render(conn, "index.json", books: Repo.all(Book))
render(conn, "show.json", book: Repo.get(Book, 1))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.