Nordikelt has asked for the wisdom of the Perl Monks concerning the following question:
Here is a simple example of what I am attempting. I start with with MyClassA which will contain an instance of MyClassB:
package MyClassA; use strict; use warnings 'all'; sub new { my $classname = shift; my $self = {}; bless($self, $classname); my %extras = @_; @$self{keys %extras} = values %extras; return $self; } sub TO_JSON { my $self = shift; return { %{$self} }; } sub setClassB { my $self = shift; $self->{MY_CLASS_B} = shift; } sub getClassB { my $self = shift; return $self->{MY_CLASS_B}; } 1;
and ,
package MyClassB; use strict; use warnings 'all'; sub new { my $classname = shift; my $self = {}; bless($self, $classname); my %extras = @_; @$self{keys %extras} = values %extras; return $self; } sub TO_JSON { my $self = shift; return { %{$self} }; } sub getName { my $self = shift; return $self->{NAME}; } 1;
Next, we build and encode MyClassA:
use strict; use warnings 'all'; use JSON::MaybeXS ':all'; use MyClassA; use MyClassB; my $a = MyClassA->new(NAME => 'A instance'); my $b = MyClassB->new(NAME => 'B instance'); $a->setClassB($b); print JSON->new()->convert_blessed()->encode($a) . "\n";
And we get output that looks good:
{"NAME":"A instance","MY_CLASS_B":{"NAME":"B instance"}}The trouble is seen when we try to read and use this JSON:
use strict; use warnings 'all'; use JSON::MaybeXS ':all'; use MyClassA; use MyClassB; my $line = <STDIN>; my $a = bless(JSON->new()->decode($line), 'MyClassA'); print $a->getClassB()->getName() . "\n";
Which yields the following error:
Can't call method "getName" on unblessed reference at test_read.pl line 12, <STDIN> line 1.I suppose I could bless(JSON->new()->decode($a->getClassB()), 'MyClassB'), but is that really the proper way to deal with this situation? Isn't there some way to bless a decoded MyClassA and get something that is blessed deeply? Thanks for your help!
|
|---|