6

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 ?

1
  • 1
    Please check module JSON::XS or JSON in www.cpan.org Commented Jul 31, 2012 at 12:13

2 Answers 2

8

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";
Sign up to request clarification or add additional context in comments.

3 Comments

It is generally better to use JSON rather then JSON::XS directly. It will use JSON::XS if available and then fallback to a pure Perl version.
Thank you very much. I used JSON::XS and sort out my issue.
For a "pretty" output: use JSON qw(encode_json) (instead of JSON::XS) and then: sub serialize { my $json = JSON->new->utf8; ... my $rslt = $json->pretty->encode($obj); ... }.
2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.