kraih/mojo — Issue #289: How About Blessed Class Support for MOJO::Json??
Author: byterock
Created: 2012-02-17 02:05:12+00:00
State: open

Seems others have asked for the so

given this little block of code

use Mojo::JSON;
my $json = Mojo::JSON->new();
my $type = Some::Class->new({id=>1,prop=>"Some Class"});
my $json_type = $json->encode($type);

print $json_type;

I would want to see some thing like this

{"id":"1","prop":"Some Class"}

however I get this

{Some::Class=HASH(0x1a57a3a4)]}

Which doesn't help me very much. I know I am specail.

Anyway I did a quick hack on Mojo::JSON

return _encode_object($value) if $ref eq 'HASH';
++ my $b = B::svref_2object($value);
++ return _encode_object($value) if $b->isa('B::PVMG');

that gives me what I want!

{"id":"1","prop":"Some Class"}

I can put together a full patch quickly if anyone esle is interesed

Of couse the one limitation is one cannot go back from JSNON into a blessed class,

so

my $type = Some::Class->new({id=>1,prop=>"Some Class"});
my $json_type = $json->encode($type);
$my_class = $json->decode($json_type);

would only give a Hash back

unless there is some sort of 'CLASS' tag passed into the decode with the class name but that is just asking for trouble.

Some other questions are what to do with Methods but I think 99% of th use would just be for the data that is in the class.

Other problems??

I could see people who use seters and gettes may be screwed as well private data my be inadvertaly exposed??