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