Skip to content

Latest commit

 

History

History
49 lines (37 loc) · 1.32 KB

README.md

File metadata and controls

49 lines (37 loc) · 1.32 KB

JsonStruct

JsonStruct is a elixir library that takes care of implementing the Jason.Encoder Protocol for a struct.

It also allows for easy renaming of keys and gives you the option to add your own encoding/decoding function for each field.

defmodule Message do
  use JsonStruct

  json_struct do
    field :to, json: "to"
    field :id, json: "msgId"

    field :message,
      json: "msg",
      encode: &String.upcase/1,
      decode: &String.downcase/1
  end
end
msg = %Message{id: "abcd", to: "José", message: "I love Elixir!"} |> Jason.encode!()
msg == ~s|{"msg":"I LOVE ELIXIR!","msgId":"abcd","to":"José"}|

Installation

If available in Hex, the package can be installed by adding json_struct to your list of dependencies in mix.exs:

def deps do
  [
    {:json_struct, "~> 0.1.0"}
  ]
end

Documentation can be generated with ExDoc and published on HexDocs. Once published, the docs can be found at https://hexdocs.pm/json_struct.

Inspiration

The library is inspired by Go struct tags and the rename field attribute of serde. The basic structure of the macro is inspired by ejpcmac/type_struct.