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