Dancer2
view release on metacpan or search on metacpan
lib/Dancer2/Serializer/JSON.pm view on Meta::CPAN
}
# 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 };
}
sub _decode_utf8 {
my ($bytes) = @_;
return Unicode::UTF8::decode_utf8($bytes) if $HAS_UNICODE_UTF8;
return decode( 'UTF-8', $bytes );
}
sub _ensure_characters {
my ( $entity, $strict_utf8, $self ) = @_;
return $entity if !defined $entity;
return _ensure_scalar( $entity, $strict_utf8, $self ) if !ref $entity;
if ( is_arrayref($entity) ) {
for my $i ( 0 .. $#{$entity} ) {
$entity->[$i] = _ensure_characters( $entity->[$i], $strict_utf8, $self );
}
return $entity;
}
if ( is_hashref($entity) ) {
for my $key ( keys %{$entity} ) {
my $value = $entity->{$key};
my $decoded_key = _ensure_scalar( $key, $strict_utf8, $self );
my $decoded_value =
_ensure_characters( $value, $strict_utf8, $self );
if ( $decoded_key ne $key ) {
delete $entity->{$key};
$entity->{$decoded_key} = $decoded_value;
} else {
$entity->{$key} = $decoded_value;
}
}
return $entity;
}
return $entity;
}
sub _ensure_scalar {
my ( $value, $strict_utf8, $self ) = @_;
return $value if utf8::is_utf8($value);
return $value if $value !~ /[\x80-\xFF]/;
return _decode_utf8($value) if _valid_utf8($value);
_invalid_utf8( $strict_utf8, $self );
return $value;
}
sub _invalid_utf8 {
my ( $strict_utf8, $self ) = @_;
my $msg = 'Invalid UTF-8 in JSON data';
$strict_utf8
and die "$msg\n";
if ( blessed($self) ) {
$self->log_cb->( warning => "$msg; leaving bytes unchanged" );
} else {
warn "$msg; leaving bytes unchanged\n";
}
}
1;
__END__
=pod
=encoding UTF-8
=head1 NAME
Dancer2::Serializer::JSON - Serializer for handling JSON data
=head1 VERSION
version 2.1.0
=head1 DESCRIPTION
This is a serializer engine that allows you to turn Perl data structures into
JSON output and vice-versa.
=head1 ATTRIBUTES
=head2 content_type
Returns 'application/json'
( run in 0.546 second using v1.01-cache-2.11-cpan-39bf76dae61 )