decebel has asked for the wisdom of the Perl Monks concerning the following question:

Sorry for spamming but after re-reading my last post, I realized it would make more sense to seek ideas about how to de-serialize json structures to blessed references in perl with blessed references containing some more blessed references (like sub-objects).

Replies are listed 'Best First'.
Re: Json and blessed references
by moritz (Cardinal) on Oct 11, 2009 at 09:50 UTC
    As Corion already told you, adding a field with the class name might help you. Then you could write a subroutine that walks the de-serialized tree, and blesses the references whenever it finds the blessed hash key.

    Of course that requires control over how the JSON is generated.

    Perl 6 - links to (nearly) everything that is Perl 6.
Re: Json and blessed references
by lamprecht (Friar) on Oct 11, 2009 at 10:21 UTC
    Hi,

    How are these JSON structures created? If two different objects reference the same (sub-) object instance, how are you going to maintain identity of that sub-object? Maybe the sources of KiokuDB would be interesting to read?


    Cheers, Christoph
Re: Json and blessed references
by bruno (Friar) on Oct 12, 2009 at 03:13 UTC
    If you are in control of the deflation of the objects, then I suggest that you use KiokuDB for this.

    { package Foo; use Moose; # Not necessary, but advisable # class definition } my $foo = Foo->new; use KiokuDB; use feature 'say'; # You can also use a file and an in-memory hash backend instead of DBI my $db = KiokuDB->new( dsn => 'dbi:SQLite:db=mydb' ); my $scope = $db->new_scope; # Store the object my $id = $db->insert($foo); undef $foo; # retrieve the object using id lookup $foo = $db->lookup($id); say ref $foo; # 'Foo'
    You can choose a file backend if you don't want to use a database (although you lose querying capabilities), and you have control over what engine is used to collapse the objects (JSON, Storable, YAML). You get the most speed with Storable, but with JSON and YAML you get readable (and possibly editable) dumps.

    It takes a little to learn, but KiokuDB::Tutorial is probably the best place to start.

Re: Json and blessed references
by dexterbt1 (Novice) on Oct 12, 2009 at 14:05 UTC

    If you happen to use Moose, MooseX::Storage supports JSON serialization among others.

    I believe the JSON output from object instances are simply a hash/dict with a key "__class__", which is what was previously suggested that you can manually do. The conversion from object to JSON and vice-versa is automatically and easily done for you by the module.

    Of course, you can do other tricks as well such as rebuild an entire class tree to/from hashes via Moose's "coercion" features. More importantly, MooseX::Storage also gives you, flexible ways/levels to customize/give hints as to "how" you want your objects serialized/deserialized.