Dancer2
view release on metacpan or search on metacpan
lib/Dancer2/Serializer/JSON.pm view on Meta::CPAN
package Dancer2::Serializer::JSON;
# ABSTRACT: Serializer for handling JSON data
$Dancer2::Serializer::JSON::VERSION = '2.1.0';
use Moo;
use Ref::Util qw< is_arrayref is_hashref >;
use JSON::MaybeXS ();
use Encode qw(decode FB_CROAK);
use Scalar::Util 'blessed';
with 'Dancer2::Core::Role::Serializer';
has '+content_type' => ( default => sub {'application/json'} );
# helpers
sub from_json { __PACKAGE__->deserialize(@_) }
sub to_json { __PACKAGE__->serialize(@_) }
sub decode_json {
my ( $entity ) = @_;
JSON::MaybeXS::decode_json($entity);
}
sub encode_json {
my ( $entity ) = @_;
JSON::MaybeXS::encode_json(_ensure_characters($entity));
}
# class definition
sub serialize {
my ( $self, $entity, $options ) = @_;
my $config = blessed $self ? $self->config : {};
my $strict_utf8 = $config->{strict_utf8};
$options ||= {};
foreach (keys %$config) {
$options->{$_} = $config->{$_} unless exists $options->{$_};
}
$options->{utf8} = 1;
exists $options->{strict_utf8}
and $strict_utf8 = delete $options->{strict_utf8};
$entity = _ensure_characters( $entity, $strict_utf8, $self );
JSON::MaybeXS->new($options)->encode($entity);
}
sub deserialize {
my ( $self, $entity, $options ) = @_;
$options ||= {};
$options->{utf8} = 1;
delete $options->{strict_utf8};
JSON::MaybeXS->new($options)->decode($entity);
}
my $HAS_UNICODE_UTF8 = eval { require Unicode::UTF8; 1; };
sub _valid_utf8 {
my ($bytes) = @_;
return Unicode::UTF8::valid_utf8($bytes) if $HAS_UNICODE_UTF8;
return eval { decode( 'UTF-8', $bytes, FB_CROAK ); 1 };
}
( run in 0.536 second using v1.01-cache-2.11-cpan-39bf76dae61 )