簡體   English   中英

Poison.Encoder如何在渲染的JSON中重命名屬性?

[英]Poison.Encoder how to rename properties in rendered JSON?

我在下面有Ecto模型。 渲染時,我希望JSON將屬性名稱“ layers”替換為“ tilemap_layers”。

我的應用程序中有許多類型的“層”,因此,當我創建數據庫架構時,我需要制作一個唯一命名的架構。 但是,此JSON將由第三方客戶端使用,該客戶端必須將其命名為“ layers”。

推薦的方法是什么?

該模型在這里:

defmodule MyProject.Tilemap do
  use MyProject.Web, :model

  @derive {Poison.Encoder, only: [
    :name,
    :tile_width,
    :tile_height,
    :width,
    :height,
    :orientation,
    :tilemap_layers,
    :tilesets
  ]}

  schema "tilemaps" do

    field :name, :string
    field :tile_width, :integer
    field :tile_height, :integer
    field :width, :integer
    field :height, :integer
    field :orientation, :string

    has_many :tilemap_layers, MyProject.TilemapLayer
    has_many :tilesets, MyProject.Tileset

    timestamps
  end

  @required_fields ~w(tile_width tile_height width height)
  @optional_fields ~w()

  @doc """
  Creates a changeset based on the `model` and `params`.

  If no params are provided, an invalid changeset is returned
  with no validation performed.
  """
  def changeset(model, params \\ :empty) do
    model
    |> cast(params, @required_fields, @optional_fields)
  end
end

使用@deriving時,毒葯無法提供別名的方法

您可以:

defimpl自己指定實現(取自docs ):

defimpl Poison.Encoder, for: Person do
  def encode(%{name: name, age: age}, _options) do
    Poison.Encoder.BitString.encode("#{name} (#{age})")
  end
end

重命名架構中的字段:

has_many :layers, MyProject.TilemapLayer

或使用Phoenix View:

defmodule MyProject.TilemapView do
  use MyProject.Web, :view

  def render("index.json", %{tilemaps: timemaps}) do
    render_many(tilemaps, __MODULE__, "tilemap.json")
  end

  def render("tilemap.json", %{tilemap: tilemap}) do
    %{
      name: tilemap.name,
      ...
      layers: render_many(layers, MyProject.TilemapLayerView, "tilemap_layer.json")
    }
  end
end

然后創建一個TilemapLayerView:

defmodule MyProject.TilemapLayerView do
  use MyProject.Web, :view

  def render("tilemap_layer.json", %{tilemap_layer: tilemap_layer}) do
    %{
      name: timemap_layer.name
    }
  end
end

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM