if json is valid utf8 mark it as such
[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
69b45b7d 10our $VERSION = '0.02';
11our $AUTHORITY = 'cpan:STEVAN';
7b428d1f 12
4d1850a6 13requires 'pack';
14requires 'unpack';
a23e18d7 15
16sub thaw {
98ae09f0 17 my ( $class, $json, @args ) = @_;
34dcaa5d 18 local $JSON::UnMapping = 1;
c9ff362a 19 utf8::encode($json) if utf8::is_utf8($json);
98ae09f0 20 $class->unpack( JSON::Any->jsonToObj($json), @args );
a23e18d7 21}
22
23sub freeze {
98ae09f0 24 my ( $self, @args ) = @_;
34dcaa5d 25 local $JSON::UnMapping = 1;
c9ff362a 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;
a23e18d7 29}
30
311;
32
33__END__
34
35=pod
36
ec9c1923 37=head1 NAME
38
39MooseX::Storage::Format::JSON
40
41=head1 SYNOPSIS
42
1390c23d 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
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
86All complex software has bugs lurking in it, and this module is no
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
96=head1 COPYRIGHT AND LICENSE
97
98Copyright 2007 by Infinity Interactive, Inc.
99
100L<http://www.iinteractive.com>
101
102This library is free software; you can redistribute it and/or modify
103it under the same terms as Perl itself.
104
a23e18d7 105=cut
106
ec9c1923 107