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 | |
|
Re^2: How to encode/decode a class inside a class in JSON
by Nordikelt (Novice) on Aug 22, 2020 at 07:01 UTC |