2017-02-26 24 views
1

我有一个Dancer2应用程序,我想使用JSON序列化程序返回一个对象的序列化版本。下面是一个小版本的它:当我尝试使用JSON序列化程序从Dancer2路由返回对象时,为什么会出现“内部服务器错误”?

{ 
    package User; 

    use Moo; 
    use Types::Standard qw/Str/; 
    has name => (is=>'ro',isa =>Str, default => ""); 

    sub TO_JSON { return { %{ shift() } };} 
} 

use Dancer2; 
set serializer => 'JSON'; 
set engines=>{serializer=>{JSON=>{allow_blessed=>1,convert_blessed=>1}}}; 

get '/hello/:name' => sub { 
    my $user = User->new({name=>route_parameters->{name}}); 
    return $user->TO_JSON; ## error if the TO_JSON method is not explicitly called. 
}; 
dance; 
1; 

如果TO_JSON方法显式调用,那么很明显的对象返回的哈希裁判,然后序列化为:

{"name":"fred"} 

作为一个例子。如果拿到最后一行是

return $user; 

,则返回以下错误:

{"title":"Error 500 - Internal Server Error","message":"","status":500,"exception":"Unrecognized response type from route: User.\n"} 

我认为设置allow_blessedconvert_blessed将处理自动调用TO_JSON,但是我无法找到有关Dancer2的文档。这是否被丢弃了?

回答

0

Dancer2不支持从路由处理程序返回任意对象。你可以只返回following types的对象:

  • 普拉克::响应
  • Dancer2 ::核心::响应
  • Dancer2 ::核心::响应延迟::

类型在序列化之前进行检查,因此如果对象类型不受支持,则序列化程序永远不会被调用。

它看起来像任意对象是supported at one point,但没有更多。正如你已经发现的,解决方法是返回一个非祝福的参考。

相关问题