Serialize and Deserialize objects to JSON (or whatever) format
What if you could serialize/deserialize objects in whatever format: JSON, XML, CSV,...; attending different criteria: export/import some properties and not others, transform values in this or that way before exporting/importing,...; and all of this without having to change the class definition? Wouldn't that be great??
Well, perhaps it's a goal too ambitious to reach 100% but, exploring this idea, I've developed a bunch of classes that I thought it was good to share. If you want to test, change, modify or improve the code, or just take a look at it, you can do it here. There you'll find a more detailed explanation (see Readme.md)
Basically, you just have to import the classes. Then choose one of your persistent or registered classes or create a new one, and change it to extend OPNLib.Serialize.Adaptor. After that, you just can do the following:
set obj = ##class(MyPkg.MyPersistentClass).%OpenId(1)
set json = obj.Export()
do json.%ToJSON()
{"prop1":"value1","prop2":"value"}
set newObj = ##class(MyPkg.MyClass).%New()
do newObj.Import(json)
write newObj.%Save()
write newObj.%Id() //if it's a persistent object, of course
27
This approach doesn't entirely avoid the need to modify the class definition yet... but once you do it, you'll have 2 methods that can act as dispatchers for whatever other serialization logic you want to inject in the future... and also, if you explore the idea behind the OPNLib.Serialize.Template class, it'll be relatively easy to adapt it to have a pre-compiled export/import methods to export/import data in whatever serialization format without modifying the source/target class.
Enjoy!
Salva, that's Great!
without having to change the class definition
I like this.

Robert
Thanks Robert! Glad you like it! It's a pity many times we include new functionalities that cannot be used for customers because is required a recompilation and a change in their class model... sometimes depending on the feature, can be strictly necessary, but I think it's not the case for exporting/importing mechanisms.
This has been implemented by the %JSON.Adaptor
https://docs.intersystems.com/irislatest/csp/docbook/Doc.View.cls?KEY=GJ...
But Salva, you were first! 👍
Yep... my solution is more flexible....no need to recompile anything to change the JSON projections (for export and import)... also it works in Caché/Ensemble... but sure it's less performant than %JSON.Adapter... less format features also... clearly I would recommend %JSON.Adapter for serious productions in IRIS.... but I had fun implementing this :-)