0

Run cpanm --look DBIx::Class ; cd examples/Schema/ to use the example database.

use 5.024;
use strictures;
use JSON::MaybeXS qw(encode_json);
use MyApp::Schema qw();
use Sub::Install qw();

my $s = MyApp::Schema->connect('dbi:SQLite:db/example.db');
# Yes, I know Helper::Row::ToJSON exists.
Sub::Install::install_sub({
    code => sub {
        my ($self) = @_;
        return { map {$_ => $self->$_} keys %{ $self->columns_info } };
    },
    into => $s->source('Track')->result_class,
    as   => 'TO_JSON',
});

my ($t) = $s->resultset('Cd')->first->tracks;
say ref $t->can('TO_JSON'); # 'CODE', ok
say ref $t->TO_JSON;        # 'HASH', ok
say encode_json $t;
# encountered object 'MyApp::Schema::Result::Track=HASH(0x1a53b48)',
# but neither allow_blessed, convert_blessed nor allow_tags settings
# are enabled (or TO_JSON/FREEZE method missing) at …

I expect the serialiser to find the installed hook and use it, but instead I get the error above. What's going wrong?

daxim
  • 39,270
  • 4
  • 65
  • 132

1 Answers1

4

In order to make JSON::XS consider TO_JSON, you have to explicitly enable convert_blessed option:

my $coder = JSON::XS->new;
$coder->convert_blessed(1);
say $coder->encode($t);

According to docs:

$json = $json->convert_blessed ([$enable])
$enabled = $json->get_convert_blessed

See "OBJECT SERIALISATION" for details.

If $enable is true (or missing), then encode, upon encountering a blessed object, will check for the availability of the TO_JSON method on the object's class. If found, it will be called in scalar context and the resulting scalar will be encoded instead of the object.

The TO_JSON method may safely call die if it wants. If TO_JSON returns other blessed objects, those will be handled in the same way. TO_JSON must take care of not causing an endless recursion cycle (== crash) in this case. The name of TO_JSON was chosen because other methods called by the Perl core (== not by the user of the object) are usually in upper case letters and to avoid collisions with any to_json function or method.

If $enable is false (the default), then encode will not consider this type of conversion.

This setting has no effect on decode.

(emphasis mine)