Converting an object from type %Library.DynamicObject to another type
I need to convert a JSON payload to a custom object type. Currently, I'm converting the JSON object to a %Library.DynamicObject object and need to proceed from here.
As of now, these are my options
1. Using an external library talked about in this link:
https://community.intersystems.com/post/binding-regular-cache-object-dynamicobject-and-vice-versa
Downside: Could be buggy (as admitted by the creator) + some other design concerns brought up in its the discussion thread
2. Creating a new object of the desired class and then Iterating through the DynamicObject and populating the new object's fields.
Downside: Having to do this for each type of object individually rather than being able to generalize it (because of the need to instantiate new objects for swizzled objects)
Is there a standard way of doing this?
IRIS for UNIX (Apple Mac OS X for x86-64) 2019.4.0DS (Build 165U)
The example below works even in Caché:
Or use %JSON.Adaptor: Exporting and Importing
Thanks Vitaliy!
I'm not sure in what version %JSON.Adaptor was introduced, but if it's in your version, you can have the class modeling your object extend %JSON.Adaptor, which will give you access to the %JSONImport() method, which can de-serialize a JSON payload into an object.
One caveat to this is that I believe any serial objects referenced by the top-level object will also need to extend %JSON.Adaptor for the import to work properly.
Thanks Jorge! This is what I'm planning to use. It does seem like an extremely large number of classes will have to be modified to extend %JSON.Adaptor.