Converting an object from type %Library.DynamicObject to another type

Primary tabs

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)

Replies

The example below works even in Caché:

#include %systemInclude n try{   $$$AddAllRoleTemporaryInTry   n $namespace   s $namespace="SAMPLES"      person=##class(Sample.Person).%OpenId(1)      ##class(%ZEN.Auxiliary.altJSONProvider).%WriteJSONStreamFromObject(.stream,person,,,$$$YES,"aeloq")   "json (string): ",stream.Read($$$MaxLocalLength),!!      ##class(%ZEN.Auxiliary.altJSONProvider).%ConvertJSONToObject(stream,"Sample.Person",.obj)   "obj.Home.Street: ",obj.Home.Street ; or d $system.OBJ.Dump(obj)    }catch(ex){   "Error "ex.DisplayString(),! }
Result: USER>^test json (string): {"Name":"Pascal,Martin F.","SSN":"502-68-5767","DOB":43307,"Home":{"Street":"9347 Franklin Drive","City":"Denver","State":"VA","Zip":66346},"Office":{"Street":"4897 Main Blvd","City":"Miami","State":"MO","Zip":60084},"Spouse":"","FavoriteColors":[],"Age":"60"} obj.Home.Street: 9347 Franklin Drive

Or use %JSON.Adaptor: Exporting and Importing

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.