Here’s how to get a free “to_json” method in every object you write. Just extend from a common introspective base class:
use MooseX::Declare;
class BaseObject {
use signatures;
use JSON::XS;
has 'id' => (isa => 'Int', is=>'ro', writer => '_id');
# and more ...
sub to_json($self) {
my $result = {};
foreach my $attr (__PACKAGE__->meta()->get_all_attributes()) {
$result->{$attr->name()} = $attr->get_value($self);
}
return encode_json($result);
}
}
Obviously this code needs to check for any objects that it should nest recursively and those that don’t support JSONification*, but that’s coming.
* = is too a word.
Advertisement
Or use MooseX::Storage which will recurse your object graph and handle contained objects.
Yes, it’s on my list to check out, though I have some other things in mind for this too