[Catalyst] Cross-link: How do I turn Moose objects into JSON for use in Catalyst?

"Alex J. G. Burzyński" mailing-catalyst at ajgb.net
Tue Aug 3 16:06:50 GMT 2010


Hi,

On 03/08/10 16:31, Evan Carroll wrote:
> I've posted a question and a few possible fixes. Does anyone have
> anything to add here? How do you go about dumping Moose to JSON in
> Cat?
>
> http://stackoverflow.com/questions/3391967/how-do-i-turn-moose-objects-into-json-for-use-in-catalyst
>
>   

That's the method I'm using to dump my classes for AJAX-driven control
panel.

Works recursively on my other moose classes (ResultSet::* classes from
DBIx::BlackBox consume MyApp::DB::ResultSet::Roles::ToJSON).

Cheers,
Alex


package MyApp::DB::ResultSet::Roles::ToJSON;

use Moose::Role;

sub TO_JSON {
    my $self = shift;

    my $json_hash = {};

    for my $attr ( $self->meta->get_all_attributes ) {
        my $name = $attr->name;
        $json_hash->{ $name } = $self->$name;
    }

    return $json_hash;    
}            
                                         
package MyApp::DB::ResultSet::SuppliersList;

use Moose;

with qw(
    MyApp::DB::ResultSet::Roles::ToJSON
); 
   
use namespace::autoclean;
           
has 'org_id' => (
    is => 'rw',
    isa => 'Str',
    required => 1,
);
has 'org_name' => (
    is => 'rw',
    isa => 'Str',
    required => 1,
);
has 'number_of_courses' => (
    is => 'rw',
    isa => 'Int',
    default => 0,
    required => 1,
); 
has 'number_of_enabled_courses' => (
    is => 'rw',
    isa => 'Int',
    default => 0,
    required => 1,
);


package MyApp::View::JSON;

use strict;
use base 'Catalyst::View::JSON';

use JSON::XS ();

my $encoder = JSON::XS
    ->new
    ->utf8
    ->pretty(0)
    ->indent(0)
    ->allow_blessed(1)
    ->convert_blessed(1);
   
sub encode_json {
    my($self, $c, $data) = @_;

    $encoder->encode($data);
}

package MyApp::Controller::Foo;
...

sub list_suppliers :Local {
    my ( $self, $c ) = @_;

    $c->stash( json => []);

    my $rs = $c->model('DB')->exec('ListSuppliers');
    do {
        while ( my $supplier = $rs->next_row ) {
            push @{ $c->stash->{json} }, $supplier;
        }
    } while ( $rs->next_resultset );

    $c->forward('View::JSON');
}



More information about the Catalyst mailing list