Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine
 
PerlMonks  

Re: How to encode/decode a class inside a class in JSON

by perlfan (Vicar)
on Aug 20, 2020 at 03:35 UTC ( [id://11120924]=note: print w/replies, xml ) Need Help??


in reply to How to encode/decode a class inside a class in JSON

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.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://11120924]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others imbibing at the Monastery: (5)
As of 2024-04-23 16:46 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found