Skip to content

Commit

Permalink
allow to map atoms to other values to handle null -> nil
Browse files Browse the repository at this point in the history
  • Loading branch information
Overbryd committed Apr 23, 2018
1 parent dfcb30c commit 4ede493
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 0 deletions.
13 changes: 13 additions & 0 deletions lib/poison/encoder.ex
Original file line number Diff line number Diff line change
Expand Up @@ -83,13 +83,15 @@ defprotocol Poison.Encoder do
@typep indent :: non_neg_integer
@typep offset :: non_neg_integer
@typep strict_keys :: boolean
@typep force :: map

@type options :: %{
optional(:escape) => escape,
optional(:pretty) => pretty,
optional(:indent) => indent,
optional(:offset) => offset,
optional(:strict_keys) => strict_keys,
optional(:force) => force,
}

@spec encode(t, options) :: iodata
Expand All @@ -103,9 +105,20 @@ defimpl Poison.Encoder, for: Atom do
def encode(true, _), do: "true"
def encode(false, _), do: "false"

def encode(atom, %{force: mapping} = options) when is_map(mapping) do
options = Map.delete(mapping, :force)
if Map.has_key?(mapping, atom) do
Map.get(mapping, atom)
|> Poison.Encoder.encode(options)
else
Encoder.BitString.encode(Atom.to_string(atom), options)
end
end

def encode(atom, options) do
Encoder.BitString.encode(Atom.to_string(atom), options)
end

end

defimpl Poison.Encoder, for: BitString do
Expand Down
2 changes: 2 additions & 0 deletions test/poison/encoder_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ defmodule Poison.EncoderTest do
assert to_json(true) == "true"
assert to_json(false) == "false"
assert to_json(:poison) == ~s("poison")
assert to_json(:null) == ~s("null")
assert to_json(:null, force: %{null: nil}) == "null"
end

test "Integer" do
Expand Down

0 comments on commit 4ede493

Please sign in to comment.