How to convert perl object to json string

I tried a lot of time to convert a Perl object to a JSON String. But still I could not find. I used JSYNC. But I saw that he has some problems. then I use the JSON module in perl. This is my code.

my $accountData = AccountsData ->new(); $accountData->userAccountsDetail(@userAccData); $accountData->creditCardDetail(@userCrData); my $json = to_json($accountData,{allow_blessed=>1,convert_blessed=>1}); print $json."\n"; 

When I run the code, it prints null . Is there any mistake I made?

+4
source share
2 answers

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"; 
+8
source

According to the docs, your object should provide the TO_JSON method, which will then use TO_JSON . It also seems that you can call JSON -convert_blessed_universally; before conversion, if you want to avoid providing your own TO_JSON method, although the docs note that this is an experimental function.

+2
source

All Articles