Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert perl object into json string

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 ?

like image 535
Amila Avatar asked Jul 31 '12 11:07

Amila


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";
like image 132
Aleksander Alekseev Avatar answered Oct 18 '22 03:10

Aleksander Alekseev


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.

like image 24
edb Avatar answered Oct 18 '22 02:10

edb