1

I'm working with moose objects in perl. I want to be able to covert the moose objects I make directly to JSON.

However, when I use use MooseX::Storage to covert the objects, it includes a hidden attribute that I don't know how to remove the "__CLASS__" .

Is there a way to remove this using MooseX::Storage ? (For now I am just using MooseX::Storage to covert it and using JSON to remove the "__ CLASS __ " attribute by going to a hash . ) The solution I am doing for now is a problem, because I have to do it everytime I get the JSON for every object(so when I write the JSON output to a file, to be loaded I have to make the changes everytime, and any referanced objects also have to be handled)

package Example::Component;
use Moose;
use MooseX::Storage;
   with Storage('format' => 'JSON');

   has 'description' => (is => 'rw', isa => 'Str');

1;
no Moose;
no MooseX::Storage;
use JSON;

my $componentObject = Example::Component->new;
$componentObject->description('Testing item with type');
my $jsonString = $componentObject->freeze();
print $jsonString."\n\n";

my $json_obj = new JSON;

my $perl_hash = $json_obj->decode ($jsonString);
delete ${$perl_hash}{'__CLASS__'};
$jsonString = $json_obj->encode($perl_hash);
print $jsonString."\n\n";
Bostwick
  • 696
  • 1
  • 12
  • 24
  • Doesn't that give you the class name of the object you're storing? Why are you trying to get rid of that? What are you trying to actually accomplish, here? –  Aug 28 '13 at 18:41
  • I am trying to work with a JSON API, the "__CLASS__" is invalid for the api I am working with and the API won't take the JSON Object – Bostwick Aug 28 '13 at 18:42

1 Answers1

1

MooseX::Storage is not particularly suited to this task. It's designed to enable persistent storage of Moose objects (that's why it adds the __CLASS__ field) so they can be retrieved by your program later.

If your goal is to construct objects for a JSON API, then it would probably be much easier to just pass your object's hashref directly to JSON.pm.

use JSON -convert_blessed_universally;

my $json_obj = JSON->new->allow_blessed->convert_blessed;
my $jsonString = $json_obj->encode( $componentObject );

The -convert_blessed_universally option (in addition to being a mouthful) will cause JSON.pm to treat blessed references (objects) as ordinary Perl structures which can be translated to JSON directly.

EDIT: Looks like you have to add the allow_blessed and convert_blessed options to the JSON object also.

friedo
  • 65,762
  • 16
  • 114
  • 184
  • There is a slight issue with this, I want to be able to push the item back into a moose object, is that possible with $json_obj->decode ? – Bostwick Aug 29 '13 at 19:19
  • 1
    Sure, but you'll need to use the constructor directly since the JSON data doesn't preserve any class association. So something like `Example::Component->new( %{ $json_obj->decode } )` – friedo Aug 29 '13 at 19:59