在这个答案中,我找到了一个简单TO_JSON
方法的推荐,这是将祝福对象序列化为 JSON 所必需的。
sub TO_JSON { return { %{ shift() } }; }
有人可以详细解释它是如何工作的吗?
我将其更改为:
sub TO_JSON {
my $self = shift; # the object itself – blessed ref
print STDERR Dumper $self;
my %h = %{ $self }; # Somehow unblesses $self. WHY???
print STDERR Dumper \%h; # same as $self, only unblessed
return { %h }; # Returns a hashref that contains a hash.
#return \%h; # Why not this? Works too…
}
很多问题...... :( 简单地说,我无法理解 3 行 Perl 代码。;(
我需要,TO_JSON
但它会过滤掉:
- 不需要的属性和
- 也未设置属性(例如,对于那些
has_${attr}
谓词返回 false 的属性)
这是我的代码——它有效,但我真的不明白为什么 unblessing 有效……</p>
use 5.010;
use warnings;
use Data::Dumper;
package Some;
use Moo;
has $_ => ( is => 'rw', predicate => 1,) for (qw(a1 a2 nn xx));
sub TO_JSON {
my $self = shift;
my $href;
$href->{$_} = $self->$_ for( grep {!/xx/} keys %$self );
# Same mysterious unblessing. The `keys` automagically filters out
# “unset” attributes without the need of call of the has_${attr}
# predicate… WHY?
return $href;
}
package main;
use JSON;
use Data::Dumper;
my @objs = map { Some->new(a1 => "a1-$_", a2 => "a2-$_", xx=>"xx-$_") } (1..2);
my $data = {arr => \@objs};
#say Dumper $data;
say JSON->new->allow_blessed->convert_blessed->utf8->pretty->encode($data);
编辑:澄清问题:
%{ $hRef }
解除引用$hRef
(获取引用指向的哈希),但为什么要从受祝福的对象引用中获取普通哈希$self
?- 换句话说,为什么
$self
是 hashref? 我试图制作一个像这样的哈希切片,@{$self}{ grep {!/xx/} keys %$self}
但它没有用。因此我创造了那个可怕TO_JSON
的 .- 如果
$self
是 hashref,为什么keys %$self
只返回具有值的属性,而不是所有声明的属性(例如 thenn
too - 参见has
)?