Kitsune.JSON

Summary

collection(label, opts \\ [])

Nest a collection of other representations in the output

property(label, opts \\ [])

Adds a single property to the eventual json output

Macros

collection(label, opts \\ [])

Nest a collection of other representations in the output.

Examples

defmodule Album do
  defstruct name: nil, songs: []
end

defmodule AlbumRepresenter do
  use Kitsune.JSON

  property :name
  collection :songs, extend: SongRepresenter, from: Song
end

album = %Album{name: "Doggystyle", songs: [song, %Song{name: "Lodi Dodi"}]}
AlbumRepresenter.to_json(album)
#=> "{"name":"Doggystyle","songs":[{"title":"Gin and Juice"},{"title":"Lodi Dodi"}]}"

json = "{"name":"Doggystyle","songs":[{"title":"Gin and Juice"},{"title":"Lodi Dodi"}]}"
AlbumRepresenter.from_json(json, Album)
#=> %Album{name: "Doggystyle", songs: [%Song{name: "Gin and Juice"}, %Song{name: "Lodi Dodi"}]}
property(label, opts \\ [])

Adds a single property to the eventual json output.

Examples

defmodule Person do
  defstruct name: nil, age: nil
end

defmodule PersonRepresenter do
  use Kitsune.JSON

  property :name
  property :age
end

person = %Person{name: "Nikki", age: 18}
PersonRepresenter.to_json(person)
#=> "{"name":"Nikki","age":18}"

json = "{"name":"Nikki","age":18}"
PersonRepresenter.from_json(json, Person)
#=> %Person{ name: "Nikki", age: 18 }

defmodule Song do
  defstruct name: nil
end

defmodule SongRepresenter do
  use Kitsune.JSON

  property :title, as: :name
end

song = %Song{name: "Gin and Juice"}
SongRepresenter.to_json(song)
#=> "{"title":"Gin and Juice"}"

json = "{"title":"Gin and Juice"}"
SongRepresenter.from_json(json, Song)
#=> %Song{name: "Gin and Juice"}