
#############################################################################
## $Id: Json.pm 6000 2006-05-02 13:43:59Z spadkins $
#############################################################################

package App::Serializer::Json;
$VERSION = (q$Revision: 6000 $ =~ /(\d[\d\.]*)/)[0];  # VERSION numbers generated by svn

use App;
use App::Serializer;
@ISA = ( "App::Serializer" );

use strict;

=head1 NAME

App::Serializer::Json - Interface for serialization and deserialization

=head1 SYNOPSIS

    use App;

    $context = App->context();
    $serializer = $context->service("Serializer");  # or ...
    $serializer = $context->serializer();
    $data = {
        an => 'arbitrary',
        collection => [ 'of', 'data', ],
        of => {
            arbitrary => 'depth',
        },
    };
    $json = $serializer->serialize($data);
    $data = $serializer->deserialize($json);
    print $serializer->dump($data), "\n";

=head1 DESCRIPTION

A Serializer allows you to serialize a structure of data
of arbitrary depth to a scalar and deserialize it back to the
structure.

The Json serializer uses JSON data structure syntax as the serialized
form of the data.  It uses the JSON module from CPAN to perform
the deserialization and serialization.

=cut

use JSON;

use constant true => JSON::true;
use constant false => JSON::false;
use constant null => JSON::null;

sub serialize {
    &App::sub_entry if ($App::trace);
    my ($self, $perl_scalar) = @_;
    my $json_text = to_json($perl_scalar, {utf8 => 1, pretty => 1, allow_blessed => 1, convert_blessed => 1});
    &App::sub_exit($json_text) if ($App::trace);
    return($json_text);
}

sub deserialize {
    &App::sub_entry if ($App::trace);
    my ($self, $json_text) = @_;
    my $perl_scalar = from_json($json_text, {utf8 => 1});
    &App::sub_exit($perl_scalar) if ($App::trace);
    return($perl_scalar);
}

sub serialized_content_type {
    #'application/json';
    'text/plain';
}

1;

