adding in some basic change info
[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.03';
11 our $AUTHORITY = 'cpan:STEVAN';
12
13 requires 'pack';
14 requires 'unpack';
15
16 sub thaw {
17     my ( $class, $json, @args ) = @_;
18     local $JSON::UnMapping = 1;
19     utf8::encode($json) if utf8::is_utf8($json);
20     $class->unpack( JSON::Any->jsonToObj($json), @args );
21 }
22
23 sub freeze {
24     my ( $self, @args ) = @_;
25     local $JSON::UnMapping = 1;
26     my $json = JSON::Any->objToJson( $self->pack(@args) );
27     utf8::decode($json) if !utf8::is_utf8($json) and utf8::valid($json); # if it's valid utf8 mark it as such
28     return $json;
29 }
30
31 1;
32
33 __END__
34
35 =pod
36
37 =head1 NAME
38
39 MooseX::Storage::Format::JSON
40
41 =head1 SYNOPSIS
42
43   package Point;
44   use Moose;
45   use MooseX::Storage;
46   
47   with Storage('format' => 'JSON');
48   
49   has 'x' => (is => 'rw', isa => 'Int');
50   has 'y' => (is => 'rw', isa => 'Int');
51   
52   1;
53   
54   my $p = Point->new(x => 10, y => 10);
55   
56   ## methods to freeze/thaw into 
57   ## a specified serialization format
58   ## (in this case JSON)
59   
60   # pack the class into a JSON string
61   $p->freeze(); # { "__CLASS__" : "Point", "x" : 10, "y" : 10 }
62   
63   # unpack the JSON string into a class
64   my $p2 = Point->thaw('{ "__CLASS__" : "Point", "x" : 10, "y" : 10 }');  
65
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
86 All complex software has bugs lurking in it, and this module is no 
87 exception. If you find a bug please either email me, or add the bug
88 to cpan-RT.
89
90 =head1 AUTHOR
91
92 Chris Prather E<lt>chris.prather@iinteractive.comE<gt>
93
94 Stevan Little E<lt>stevan.little@iinteractive.comE<gt>
95
96 Yuval Kogman E<lt>yuval.kogman@iinteractive.comE<gt>
97
98 =head1 COPYRIGHT AND LICENSE
99
100 Copyright 2007 by Infinity Interactive, Inc.
101
102 L<http://www.iinteractive.com>
103
104 This library is free software; you can redistribute it and/or modify
105 it under the same terms as Perl itself.
106
107 =cut
108
109