[dancer-users] Returning JSON Data

Kadir Beyazlı kadirbeyazli at gmail.com
Sun Sep 13 17:54:15 BST 2015


Hi All,

I will return JSON data from a route.
If I don't use Dancer2 framework, I do it as follow and it works:

sub json_branch_list {

  my $sth_branch = $dbh->prepare
    (qq(SELECT BranchID,Branch
        FROM branch
        WHERE Deleted=0
       ));

  $sth_branch->execute || die 'SQL_ERROR';

  my $branch_list = [];

  while (my $branch = $sth_branch->fetchrow_hashref) {

    push @$branch_list,
      { BranchID => $branch->{BranchID},
    Branch   => $branch->{Branch}
      };
  }

  use JSON;

  my $result = { total   => scalar(@$branch_list),
         branch  => $branch_list,
         success => JSON::true
           };

  print $q->header(-content_type => "application/json; charset='utf8');

  print to_json($result);

  exit;
}

At Dancer2, when I write below definition :

use JSON;

it does not allow with a warning that to_json and from_json functions
are duplicated. I of course know that Dancer2 is using following
definition

set serializer => 'JSON';

But I still could not achieve returnin JSON data: Here my route is

get '/json_branch_list' => sub {

  my $sth_branch = database->prepare
    (qq(SELECT BranchID,Branch
        FROM branch
        WHERE Deleted=0
       ));

  $sth_branch->execute || die 'SQL_ERROR';

  my $branch_list = [];

  while (my $branch = $sth_branch->fetchrow_hashref) {

    push @$branch_list,
      { BranchID => $branch->{BranchID},
    Branch   => $branch->{Branch}
      };
  }

  set serializer => 'JSON';

   return $branch_list;
};

No data is displayed

-- 
Kadir Beyazlı
Computer Engineer
GSM : +90 535 821 50 00


More information about the dancer-users mailing list