The Perl Toolchain Summit needs more sponsors. If your company depends on Perl, please support this very important event.
package HTTP::Entity::Parser::JSON;

use strict;
use warnings;
use JSON qw//;
use Encode qw/encode_utf8/;

sub new {
    my $class = shift;
    bless {buffer => ''}, $class;
}

sub add {
    my $self = shift;
    $self->{buffer} .= $_[0] if defined $_[0];
}

sub finalize {
    my $self = shift;

    my $p = JSON::decode_json($self->{buffer});
    my @params;
    if (ref $p eq 'HASH') {
        while (my ($k, $v) = each %$p) {
            if (ref $v eq 'ARRAY') {
                for (@$v) {
                    push @params, encode_utf8($k), encode_utf8($_);
                }
            } else {
                push @params, encode_utf8($k), encode_utf8($v); 
            }
        }
    }
    return (\@params, []);
}

1;

__END__

=encoding utf-8

=head1 NAME

HTTP::Entity::Parser::JSON - parser for application/json

=head1 SYNOPSIS

    use HTTP::Entity::Parser;
    
    my $parser = HTTP::Entity::Parser->new;
    $parser->register('application/json','HTTP::Entity::Parser::JSON');

=head1 LICENSE

Copyright (C) Masahiro Nagano.

This library is free software; you can redistribute it and/or modify
it under the same terms as Perl itself.

=head1 AUTHOR

Masahiro Nagano E<lt>kazeburo@gmail.comE<gt>

Tokuhiro Matsuno E<lt>tokuhirom@gmail.comE<gt>

=cut