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