module JSON::Serializable::Fake
Overview
JSON::Serializable::Fake allows method calls to generate JSON content.
Example
require "json/fakefield"
class Sum
include JSON::Serializable
include JSON::Serializable::Fake
property a : UInt32
property b : UInt32
def initialize(@a, @b)
end
@[JSON::FakeField]
def sum(json : ::JSON::Builder) : Nil
json.number(a + b)
end
end
s = Sum.new(10, 5)
puts s.to_json # => { "a": 10, "b": 5, "sum": 15 }
Usage
JSON::Serializable::Fake will create extend_to_json (which will actually call
your methods) and will replace the on_to_json method generated by JSON::Serializable.
JSON::Serializable::Fake is compatible with JSON::Serializable::Unmapped and
JSON::Serializable::Strict as long as JSON::Serializable::Fake is included last.
You can customize the behavior of each fake field via the JSON::FakeField annotation.
Method calls MUST accept ::JSON::Builder as a parameter and return ::Nil. The
construction of JSON elements is handled via ::JSON::Builder.
JSON::FakeField properties:
- key: an explicit name of the field added to the json string (by default it uses the method name)
- suppress_key: if
trueno json field will be implictly added. This allows the method call to create multiple json fields
WARNING At the moment it is not possible to deserialize fake fields into a method call. There is no technical limitation,
just a lack of time. However, you can use JSON::Serializable::Unmapped to capture all the fake fields.
Defined in:
json-serializable-fake.cr:3json-serializable-fake.cr:61
Constant Summary
-
VERSION =
"0.0.1"
Instance Method Summary
-
#to_json(json : JSON::Builder)
heavily modelled after: https://github.com/crystal-lang/crystal/blob/fda656c71/src/json/serialization.cr#L181
Instance Method Detail
heavily modelled after: https://github.com/crystal-lang/crystal/blob/fda656c71/src/json/serialization.cr#L181