Rework ::XS serializer and deserializer classes
[catagits/Catalyst-Action-REST.git] / lib / Catalyst / Action / Serialize / JSON.pm
CommitLineData
e601adda 1package Catalyst::Action::Serialize::JSON;
2
930013e6 3use Moose;
4use namespace::autoclean;
8d507a2f 5BEGIN {
6 $ENV{'PERL_JSON_BACKEND'} = 2; # Always use compiled JSON::XS
7}
e601adda 8
930013e6 9extends 'Catalyst::Action';
14cbe8f1 10use JSON ();
e601adda 11
8004a60b 12our $VERSION = '1.00';
f465980c 13$VERSION = eval $VERSION;
14
14cbe8f1 15has encoder => (
16 is => 'ro',
17 lazy_build => 1,
18);
19
20sub _build_encoder {
21 my $self = shift;
22 return JSON->new->utf8->convert_blessed;
23}
24
e601adda 25sub execute {
26 my $self = shift;
27 my ( $controller, $c ) = @_;
28
faf5c20b 29 my $stash_key = (
07682cbc 30 $controller->{'serialize'} ?
31 $controller->{'serialize'}->{'stash_key'} :
14cbe8f1 32 $controller->{'stash_key'}
faf5c20b 33 ) || 'rest';
7f36b63e 34 my $output = $self->serialize( $c->stash->{$stash_key} );
e601adda 35 $c->response->output( $output );
36 return 1;
37}
38
485b5160 39sub serialize {
546f2871 40 my $self = shift;
14cbe8f1 41 my $data = shift;
42 $self->encoder->encode( $data );
546f2871 43}
44
24748286 45__PACKAGE__->meta->make_immutable;
46
e601adda 471;