2015-11-17 51 views
1

我有下面的Ecto模型。當我渲染時,我希望JSON用屬性名稱「layers」替換「tilemap_layers」。Poison.Encoder如何重命名呈現的JSON中的屬性?

我的應用程序中有很多'圖層'類型,所以當我創建我的數據庫模式時,我需要創建一個唯一命名的模式。但是,此JSON將由第三方客戶端使用,必須將其命名爲「圖層」。

這樣做的建議方法是什麼?

該模型是在這裏:

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 

回答

3

毒不提供一種方式來別名使用@deriving

時,您可以:

自行指定執行與defimpl(從the 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

或使用鳳凰查看:

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:

+0

再次感謝Gazler!我正在嘗試foreign_key選項,因爲這是我真正想要的 –

+0

Woot!這工作!我確實需要改變一個小的錯字。我改變了foreign_key :: tilemap_id –

+0

@JoshPetitt你可能不需要實際指定'foreign_key'。你可以試試嗎? – Gazler