How to convert Perl objects into JSON and vice versa -


i have defined point object in file point.pm following:

package point; sub new {     ($class) = @_;     $self = {         _x => 0,         _y => 0,     };     return bless $self => $class; }  sub x {     ($self, $x) = @_;     $self->{_x} = $x if defined $x;     return $self->{_x}; }  sub y {     ($self, $y) = @_;     $self->{_y} = $y if defined $y;     return $self->{_y}; }  1; 

now when use json convert object json following code:

use json; use point;  point $p = new point; $p->x(20); $p->y(30);  $json = encode_json $p; 

i following error:

encountered object 'point=hash(0x40017288)', neither allow_blessed nor convert_blessed settings enabled @ test.pl line 28 

how convert , json object using json module?

well warning tells wrong. json not deal blessed references (i.e. objects) unless tell do:

you can convert_blessed , can allow_blessed. allow_blessed, says:

if $enable false (the default), encode throw exception when encounters blessed object.

point object class, instance of point blessed reference, , default json throw exception.

if enable convert_blessed, call to_json method on object. simple objects point (ones contain no blessed members), can as:

sub to_json { return { %{ shift() } }; } 

if have descend structure, lot hairier.


somebody in comments below said didn't cover how objects out of json.

the basics simple. here goes

my $object = bless( json->new->decode( $json_string ), 'classiwant' ); 

i covered part prevents serializing blessed object json.

the basics of deserialization simple, basics of serialization simple--once know trick. there no error in way, there task of finding need , blessing right class.

if want have code coupled objects, you'll know has blessed , have blessed into. if want totally decoupled code, this no harder or easier in perl in javascript itself.

you're going have serialize marker in json. if need this, insert '__class__' field blessed objects. , when deserializing, descend through structure , bless this:

 bless( $ref, delete $ref->{__class__} ); 

but said, no easier or harder in perl, because json presents same challenge languages.

as schwern suggested in comment top, yaml better built serializing , deserializing objects, because has notation it. json gives associative arrays or arrays.


Comments

Popular posts from this blog

android - Spacing between the stars of a rating bar? -

aspxgridview - Devexpress grid - header filter does not work if column is initially hidden -

c# - How to execute a particular part of code asynchronously in a class -