NAME
Class::JSON_Object - Role for Class::JSON_Object
SYNOPSIS
use Object::Pad;
class Action :does(Class::JSON_Object) {
field $operation;
field $arg;
}
# Create instance and load from JSON.
my $op = Action->new->load('{"operation":"move","arg":42}');
my $op = Action->create('{"operation":"move","arg":42}');
# Accessors are automatically provided.
say "Operation = ", $op->operation;
say "Arg = ", $op->arg;
DESCRIPTION
Many web services and apps exchange information in the form of JavaScript objects in JSON format. This class, actually a role, makes it easy to define classes that construct Perl objects that correspond to the JSON objects.
The intention is that these Perl objects can easily be loaded from, and serialized as JSON. However, they are useful for data classs too, even without the JSON.
For example:
class MyClass :does(Class::JSON_Object);
# Fields, must be passed as params upon creation:
field $myfield1 :param
# All fields automatically get an accessor (even arrays and hashes).
# Fields, filled in later:
field $myfield2 :mutator;
# Fields with preset values, add mutator if required:
field $myfield2 = "some value";
# Fields that hold objects:
field $myfield3 :Class(SomeOtherDataClass);
# Fields that are optional, with defaul value.
field $myfield4 :Optional = "42";
CONSTRUCTOR
Class::JSON_Object is a role, and not constructed.
create( $data ) =head2 create_sparse( $data )
Creates the object and loads from the given data.
The data may be a hash or a JSON string.
The sparse variant allows the data to contain fields that are not defined as part of the class.
Returns the object for convenience.
load( $data ) =head2 load_sparse( $data )
Loads the object from the given data.
The data may be a hash or a JSON string.
The sparse variant allows the data to contain fields that are not defined as part of the class.
Returns the object for convenience.
hash()
Produce a plain hash from the object.
json()
Produce a JSON string from the object.
METHODS
json2perl( $json )
Serialization helper. Decodes the JSON string and returns it as a Perl hash.
json2perl( $json )
Serialization helper. Encodes a Perl hash as a JSON string and returns it as .
AUTHOR
Johan Vromans, <JV at cpan.org>
SUPPORT AND DOCUMENTATION
Development of this module takes place on GitHub: https://github.com/sciurius/perl-Class-JSON_Object.
You can find documentation for this module with the perldoc command.
perldoc Class::JSON_Object
Please report any bugs or feature requests using the issue tracker on GitHub.
SEE ALSO
ACKNOWLEDGEMENTS
COPYRIGHT & LICENSE
Copyright 2024 Johan Vromans, all rights reserved.
This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.