module JSON::Serializable
Overview
The JSON::Serializable
module automatically generates methods for JSON serialization when included.
Example
require "json"
class Location
include JSON::Serializable
@[JSON::Field(key: "lat")]
property latitude : Float64
@[JSON::Field(key: "lng")]
property longitude : Float64
end
class House
include JSON::Serializable
property address : String
property location : Location?
end
house = House.from_json(%({"address": "Crystal Road 1234", "location": {"lat": 12.3, "lng": 34.5}}))
house.address # => "Crystal Road 1234"
house.location # => #<Location:0x10cd93d80 @latitude=12.3, @longitude=34.5>
house.to_json # => %({"address":"Crystal Road 1234","location":{"lat":12.3,"lng":34.5}})
houses = Array(House).from_json(%([{"address": "Crystal Road 1234", "location": {"lat": 12.3, "lng": 34.5}}]))
houses.size # => 1
houses.to_json # => %([{"address":"Crystal Road 1234","location":{"lat":12.3,"lng":34.5}}])
Usage
Including JSON::Serializable
will create #to_json
and self.from_json
methods on the current class,
and a constructor which takes a JSON::PullParser
. By default, these methods serialize into a json
object containing the value of every instance variable, the keys being the instance variable name.
Most primitives and collections supported as instance variable values (string, integer, array, hash, etc.),
along with objects which define to_json and a constructor taking a JSON::PullParser
.
Union types are also supported, including unions with nil. If multiple types in a union parse correctly,
it is undefined which one will be chosen.
To change how individual instance variables are parsed and serialized, the annotation JSON::Field
can be placed on the instance variable. Annotating property, getter and setter macros is also allowed.
require "json"
class A
include JSON::Serializable
@[JSON::Field(key: "my_key", emit_null: true)]
getter a : Int32?
end
JSON::Field
properties:
- ignore: if
true
skip this field in serialization and deserialization (by default false) - ignore_serialize: If truthy, skip this field in serialization (default:
false
). The value can be any Crystal expression and is evaluated at runtime. - ignore_deserialize: if
true
skip this field in deserialization (by default false) - key: the value of the key in the json object (by default the name of the instance variable)
- root: assume the value is inside a JSON object with a given key (see
Object.from_json(string_or_io, root)
) - converter: specify an alternate type for parsing and generation. The converter must define
from_json(JSON::PullParser)
andto_json(value, JSON::Builder)
. Examples of converters are aTime::Format
instance andTime::EpochConverter
forTime
. - presence: if
true
, a@{{key}}_present
instance variable will be generated when the key was present (even if it has anull
value),false
by default - emit_null: if
true
, emits anull
value for nilable property (by default nulls are not emitted)
Deserialization also respects default values of variables:
require "json"
struct A
include JSON::Serializable
@a : Int32
@b : Float64 = 1.0
end
A.from_json(%<{"a":1}>) # => A(@a=1, @b=1.0)
Extensions: JSON::Serializable::Strict
and JSON::Serializable::Unmapped
.
If the JSON::Serializable::Strict
module is included, unknown properties in the JSON
document will raise a parse exception. By default the unknown properties
are silently ignored.
If the JSON::Serializable::Unmapped
module is included, unknown properties in the JSON
document will be stored in a Hash(String, JSON::Any)
. On serialization, any keys inside json_unmapped
will be serialized and appended to the current json object.
require "json"
struct A
include JSON::Serializable
include JSON::Serializable::Unmapped
@a : Int32
end
a = A.from_json(%({"a":1,"b":2})) # => A(@json_unmapped={"b" => 2}, @a=1)
a.json_unmapped["b"].raw.class # => Int64
a.to_json # => %({"a":1,"b":2})
Class annotation JSON::Serializable::Options
supported properties:
- emit_nulls: if
true
, emits anull
value for all nilable properties (by default nulls are not emitted)
require "json"
@[JSON::Serializable::Options(emit_nulls: true)]
class A
include JSON::Serializable
@a : Int32?
end
Discriminator field
A very common JSON serialization strategy for handling different objects under a same hierarchy is to use a discriminator field. For example in GeoJSON each object has a "type" field, and the rest of the fields, and their meaning, depend on its value.
You can use JSON::Serializable.use_json_discriminator
for this use case.
after_initialize
method
#after_initialize
is a method that runs after an instance is deserialized
from JSON. It can be used as a hook to post-process the initialized object.
Example:
require "json"
class Person
include JSON::Serializable
getter name : String
def after_initialize
@name = @name.upcase
end
end
person = Person.from_json %({"name": "Jane"})
person.name # => "JANE"
Direct including types
- GoogleDrive::About
- GoogleDrive::AboutDriveThemesInner
- GoogleDrive::AboutStorageQuota
- GoogleDrive::AboutTeamDriveThemesInner
- GoogleDrive::Change
- GoogleDrive::ChangeList
- GoogleDrive::Channel
- GoogleDrive::Comment
- GoogleDrive::CommentList
- GoogleDrive::CommentQuotedFileContent
- GoogleDrive::ContentRestriction
- GoogleDrive::Drive
- GoogleDrive::DriveBackgroundImageFile
- GoogleDrive::DriveCapabilities
- GoogleDrive::DriveList
- GoogleDrive::DriveRestrictions
- GoogleDrive::File
- GoogleDrive::FileCapabilities
- GoogleDrive::FileContentHints
- GoogleDrive::FileContentHintsThumbnail
- GoogleDrive::FileImageMediaMetadata
- GoogleDrive::FileImageMediaMetadataLocation
- GoogleDrive::FileLabelInfo
- GoogleDrive::FileLinkShareMetadata
- GoogleDrive::FileList
- GoogleDrive::FileShortcutDetails
- GoogleDrive::FileVideoMediaMetadata
- GoogleDrive::GeneratedIds
- GoogleDrive::Label
- GoogleDrive::LabelField
- GoogleDrive::LabelFieldModification
- GoogleDrive::LabelList
- GoogleDrive::LabelModification
- GoogleDrive::ModifyLabelsRequest
- GoogleDrive::ModifyLabelsResponse
- GoogleDrive::Permission
- GoogleDrive::PermissionList
- GoogleDrive::PermissionPermissionDetailsInner
- GoogleDrive::PermissionTeamDrivePermissionDetailsInner
- GoogleDrive::Reply
- GoogleDrive::ReplyList
- GoogleDrive::Revision
- GoogleDrive::RevisionList
- GoogleDrive::StartPageToken
- GoogleDrive::TeamDrive
- GoogleDrive::TeamDriveBackgroundImageFile
- GoogleDrive::TeamDriveCapabilities
- GoogleDrive::TeamDriveList
- GoogleDrive::TeamDriveRestrictions
- GoogleDrive::User
Defined in:
ext/json/serialization.crClass Method Summary
-
.build_from_hash(hash : JSON::Any)
Builds the object from a JSON::Any hash @param [Hash] JSON::Any @return [Object] Returns the model itself
Instance Method Summary
-
#to_hash : JSON::Any
Returns the object in the form of hash @return [Hash] Returns the object in the form of hash
Class Method Detail
Builds the object from a JSON::Any hash @param [Hash] JSON::Any @return [Object] Returns the model itself
Instance Method Detail
Returns the object in the form of hash @return [Hash] Returns the object in the form of hash