First version:
use JSON::XS; use Data::Structure::Util qw/unbless/; sub serialize { my $obj = shift; my $class = ref $obj; unbless $obj; my $rslt = encode_json($obj); bless $obj, $class; return $rslt; } sub deserialize { my ($json, $class) = @_; my $obj = decode_json($json); return bless($obj, $class); }
Second version:
package SerializablePoint; use strict; use warnings; use base 'Point'; sub TO_JSON { return { %{ shift() } }; } 1; package main; use strict; use warnings; use SerializablePoint; use JSON::XS; my $point = SerializablePoint->new(10, 20); my $json = JSON::XS->new->convert_blessed->encode($point); print "$json\n"; print "point: x = ".$point->get_x().", y = ".$point->get_y()."\n";
source share