[dancer-users] JSON serializer, returning object instances form route handlers, convert_blessed

John Barrett john at jbrt.org
Wed Apr 15 17:55:11 BST 2015


Hey all,

Usually in instances like this, I assume I am doing something wrong and
am curious to know what it is...

I would expect to be able to return any instance which implements
TO_JSON directly from my route handler and have the JSON serializer
(configured with convert_blessed => 1) pull its data from that method.

This test app demonstrates what I am doing, I think. Visiting '/' gives
me (pretty, demonstrating the config is read) JSON output. Visiting
'/object' results in:

Route exception: Unrecognized response type from route: AnObject.
in ....perl5/lib/perl5/Return/MultiLevel.pm l. 97

package JsonTest;

use Dancer2;

set engines => {
    serializer => {
        JSON => {
            convert_blessed => 1,
            pretty          => 1,
        }
    }
};
set serializer => 'JSON';

get '/' => sub {
    { key => 'value', 'key2' => 'value2' };
};

get '/object' => sub {
    AnObject->new;
};

package AnObject {
    use Moo;

    sub TO_JSON {
        { is => ref shift };
    }
}

1;

I can, of course, call to_json/from_json with the appropriate options /
headers myself (this works), but would like to take advantage of the
convenience of the serializer.

Thanks!


More information about the dancer-users mailing list