2017-07-03 53 views
0

运行cpanm --look DBIx::Class ; cd examples/Schema/使用示例数据库。为什么JSON说串行化钩子丢失了?

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 … 

我期望serialiser能够找到安装好的挂钩并使用它,但是我却得到了上面的错误。出了什么问题?

+0

欢迎回来:) – simbabque

回答

4

为了使JSON::XS考虑TO_JSON,你必须明确地启用convert_blessed选项:

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

根据docs

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

请参阅 “对象序列化” 的说明。

如果$ enable为true(或缺失),则在遇到祝福对象时进行编码,将检查对象类上TO_JSON方法 的可用性。如果找到,将在标量上下文中调用 ,并且生成的标量将被编码而不是该对象。

如果需要,TO_JSON方法可以安全地调用die。如果TO_JSON返回其他祝福的对象,那么将以相同的方式处理这些对象。 在这种情况下,TO_JSON必须注意不要造成无限的递归循环(== 崩溃)。 TO_JSON的名称被选中是因为Perl核心调用的其他方法(==不是该对象的用户)是 ,通常采用大写字母,并避免与任何to_json 函数或方法冲突。

如果$启用为假(默认值),则编码不会考虑这种类型的转换。

此设置对解码没有影响。

(重点煤矿)

相关问题