in reply to How to encode/decode a class inside a class in JSON

This is called coercion or unmarshalling. Using Moo + Types::Standard makes it pretty easy...

use v5.12; use strict; use warnings; package ToJson { use Moo::Role; sub TO_JSON { my $self = shift; return { %$self }; } } package Named { use Moo::Role; use Types::Standard -types; has NAME => ( is => 'bare', isa => Str, reader => 'getName', ); } package MyClassA { use Moo; use Types::Standard -types; with 'ToJson', 'Named'; has MY_CLASS_B => ( is => 'bare', reader => 'getClassB', writer => 'setClassB', isa => InstanceOf->of('MyClassB')->plus_constructors( Has +hRef, 'new' ), coerce => 1, ); } package MyClassB { use Moo; with 'ToJson', 'Named'; } use JSON::MaybeXS; my $a = MyClassA->new(NAME => 'A instance'); my $b = MyClassB->new(NAME => 'B instance'); $a->setClassB($b); my $json = JSON->new->convert_blessed->encode($a); say $json; my $inflated = MyClassA->new( JSON->new->decode($json) ); say $inflated->getClassB->getName;

The key part is this:

isa => InstanceOf->of('MyClassB')->plus_constructors( Has +hRef, 'new' ), coerce => 1,

This means that when the MY_CLASS_B attribute gets passed a hashref instead of an instance of MyClassB, it should call MyClassB->new on that hashref. This coercion happens in both the constructor (new) and the attribute writer (setClassB).

Of course, it can be done without Moo or Types::Standard. They're not magic. To do it manually, alter your MyClassA::new to check %extras to find if there's any values that need inflating. Something like this:

if ( exists $extras{MY_CLASS_B} and ref $extras{MY_CLASS_B} eq 'HA +SH' ) { $extras{MY_CLASS_B} = MyClassB->new( %{ $extras{MY_CLASS_B} } +); }

And probably a good idea to do something similar in setClassB. Allow it to accept a hashref and inflate it to a MyClassB object.

Replies are listed 'Best First'.
Re^2: How to encode/decode a class inside a class in JSON
by tobyink (Canon) on Aug 20, 2020 at 15:15 UTC

    Obligatory Zydeco example...

    use v5.12; use strict; use warnings; use JSON::MaybeXS; package MyApp { use Zydeco; role ToJson { method TO_JSON { return { %$self }; } } role Named { has NAME ( is => bare, type => Str, reader => 'getName', ); } class MyClassA with ToJson, Named { has MY_CLASS_B ( is => bare, reader => 'getClassB', writer => 'setClassB', type => 'MyClassB', ); } class MyClassB with ToJson, Named { coerce from HashRef via new; } } my $a = MyApp->new_myclassa( NAME => 'A instance' ); my $b = MyApp->new_myclassb( NAME => 'B instance' ); $a->setClassB($b); my $json = JSON->new->convert_blessed->encode($a); say $json; my $inflated = MyApp->new_myclassa( JSON->new->decode($json) ); say $inflated->getClassB->getName;
Re^2: How to encode/decode a class inside a class in JSON
by Nordikelt (Novice) on Aug 22, 2020 at 07:01 UTC

    Wow, that was quite the lesson. A lot of stuff packed in there that was new to me, but I believe I understand it now.

    Thanks much for your help!