This:
sub TO_JSON { my $self = shift; return { %{$self} }; }

needs to return a string.

If you need to encode a data structure that may contain objects, you usually need to look into the structure and replace objects with alternative non-blessed values, or enable convert_blessed and provide a TO_JSON method for each object's (base) class that may be found in the structure, in order to let the methods replace the objects with whatever scalar values the methods return.

See #2 in "Object Serialization" section of JSON.

Nevermind, I misread your question. Under "Deserialization", there is the section about implementing a THAW method. I have never tried this, but the docs imply the FREEZE method needs provide the needed information needed for your THAW implementation.

In the past when I've done something like this, I passed the module name as an additional field in the serialized JSON. Then I eval'd the constuctor using the relevant decoded JSON string as the input to said constructor. I am not recommending that, but it was long ago before I thought to look at how to handle this properly in the JSON family of modules. I didn't even use TO_JSON, which I should have. I certainly didn't use FREEZE or THAW. Today I'd try to do it that way.


In reply to Re: How to encode/decode a class inside a class in JSON by perlfan
in thread How to encode/decode a class inside a class in JSON by Nordikelt

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.