New option json_options_encode to set JSON options for output
[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;
e601adda 5
930013e6 6extends 'Catalyst::Action';
aadb0c7d 7use JSON::MaybeXS qw(JSON);
e601adda 8
14cbe8f1 9has encoder => (
10 is => 'ro',
11 lazy_build => 1,
12);
13
14sub _build_encoder {
15 my $self = shift;
16 return JSON->new->utf8->convert_blessed;
17}
18
e601adda 19sub execute {
20 my $self = shift;
21 my ( $controller, $c ) = @_;
22
43e4baa3 23 if (my $options = $controller->{json_options_encode}) {
24 foreach my $opt (keys %$options) {
25 $self->encoder->$opt( $options->{$opt} );
26 }
27 }
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;