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( HashRef, '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;