I tried lot of time to convert perl object into JSON String. But still i couldn't found. i used JSYNC. But i saw it has some issues. then i use 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 have done ?
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";
According to the docs, your object must provide a TO_JSON
method, which to_json
will then use. It also seems to imply that you could call JSON -convert_blessed_universally;
before conversion if you wanted to avoid providing your own TO_JSON
method, though the docs note that that's an experimental feature.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With