Version 0.32
[gitmo/MooseX-Storage.git] / lib / MooseX / Storage / Format / JSON.pm
CommitLineData
a23e18d7 1
4d1850a6 2package MooseX::Storage::Format::JSON;
a23e18d7 3use Moose::Role;
4
34dcaa5d 5no warnings 'once';
6
b5384d08 7use JSON::Any;
c9ff362a 8use utf8 ();
a23e18d7 9
e44b5f54 10our $VERSION = '0.32';
69b45b7d 11our $AUTHORITY = 'cpan:STEVAN';
7b428d1f 12
4d1850a6 13requires 'pack';
14requires 'unpack';
a23e18d7 15
16sub thaw {
98ae09f0 17 my ( $class, $json, @args ) = @_;
c9ff362a 18 utf8::encode($json) if utf8::is_utf8($json);
0edcbfee 19 $class->unpack( JSON::Any->new->jsonToObj($json), @args );
a23e18d7 20}
21
22sub freeze {
98ae09f0 23 my ( $self, @args ) = @_;
0edcbfee 24 my $json = JSON::Any->new->objToJson( $self->pack(@args) );
c9ff362a 25 utf8::decode($json) if !utf8::is_utf8($json) and utf8::valid($json); # if it's valid utf8 mark it as such
26 return $json;
a23e18d7 27}
28
f82612bc 29no Moose::Role;
30
a23e18d7 311;
32
33__END__
34
35=pod
36
ec9c1923 37=head1 NAME
38
4fa64e86 39MooseX::Storage::Format::JSON - A JSON serialization role
ec9c1923 40
41=head1 SYNOPSIS
42
1390c23d 43 package Point;
44 use Moose;
45 use MooseX::Storage;
ec725183 46
1390c23d 47 with Storage('format' => 'JSON');
ec725183 48
1390c23d 49 has 'x' => (is => 'rw', isa => 'Int');
50 has 'y' => (is => 'rw', isa => 'Int');
ec725183 51
1390c23d 52 1;
ec725183 53
1390c23d 54 my $p = Point->new(x => 10, y => 10);
ec725183 55
56 ## methods to freeze/thaw into
1390c23d 57 ## a specified serialization format
58 ## (in this case JSON)
ec725183 59
1390c23d 60 # pack the class into a JSON string
61 $p->freeze(); # { "__CLASS__" : "Point", "x" : 10, "y" : 10 }
ec725183 62
1390c23d 63 # unpack the JSON string into a class
ec725183 64 my $p2 = Point->thaw('{ "__CLASS__" : "Point", "x" : 10, "y" : 10 }');
1390c23d 65
ec9c1923 66=head1 METHODS
67
68=over 4
69
70=item B<freeze>
71
72=item B<thaw ($json)>
73
74=back
75
76=head2 Introspection
77
78=over 4
79
80=item B<meta>
81
82=back
83
84=head1 BUGS
85
ec725183 86All complex software has bugs lurking in it, and this module is no
ec9c1923 87exception. If you find a bug please either email me, or add the bug
88to cpan-RT.
89
90=head1 AUTHOR
91
92Chris Prather E<lt>chris.prather@iinteractive.comE<gt>
93
94Stevan Little E<lt>stevan.little@iinteractive.comE<gt>
95
6c9f2c85 96Yuval Kogman E<lt>yuval.kogman@iinteractive.comE<gt>
97
ec9c1923 98=head1 COPYRIGHT AND LICENSE
99
1f3074ea 100Copyright 2007-2008 by Infinity Interactive, Inc.
ec9c1923 101
102L<http://www.iinteractive.com>
103
104This library is free software; you can redistribute it and/or modify
105it under the same terms as Perl itself.
106
a23e18d7 107=cut
108
ec9c1923 109