Saw the other day an article with the usage of the %ZEN
package when working with JSON and decided to write an article describing a more modern approach. At some recent point, there was a big switch from using %ZEN.Auxiliary.*
to dedicated JSON classes. This allowed to work with JSONs more organically.
Thus, at this point there are basically 3 main classes to work with JSON:
-
%Library.DynamicObject
- provides a simple and efficient way to encapsulate and work with standard JSON documents. Also, there is a possibility instead of writing the usual code for creating an instance of a class like
set obj = ##class(%Library.DynamicObject).%New()
it is possible to use the following syntax
set obj = {}
-
%Library.DynamicArray
- provides a simple yet efficient way to encapsulate and work with standard JSON arrays. With arrays you can use the same approach as with objects, meaning that yu can either create an instance of the class
set array = ##class(%DynamicArray).%New()
or you can do it by using brackets []
set array = []
-
%JSON.Adaptor
is a means for mapping ObjectScript objects (registered, serial or persistent) to JSON text or dynamic entities.
Let's look at them a bit closer.
Let's say I'm working with a RESTful client and I need to send some info generated on the go that's not a database object but some parts of it. I can just create a new instance of %DynamicObject and just set it's properties. In a way, it's similar to what was done before with %ZEN.ProxyObject
. And of course, I can have built-in objects and built-in arrays as properties (or JSON fields):
Set result={}
set result.Group = "TB-41"
set result.Name = "Iryna Mykhailova"
set result.Questions = ["What is JSON?", "Create instance of class Test and set all it's properties."]
As a result of these lines of code, we will get the following JSON string:
{"Group":"TB-41","Name":"Iryna Mykhailova","Questions":["What is JSON?","Create instance of class Test and set all it's properties."]}
</p> </div>
Apart from just setting the properties or simply writing the JSON string inside the brackets
Set result={"Group":"TB-41", "Name":"Iryna Mykhailova", "Questions":["What is JSON?", "Create instance of class Test and set all it's properties."]}
there is a possibility to use methods to set ( %Set() ), get ( %Get() ) and delete ( %Remove() ) the values of the properties. The same is true for the arrays.
And the last basic class %JSON.Adaptor
is used as a superclass to enable JSON capabilities to the existing classes. So if there is a class data from which is used in RESTful service, it's easy to get a JSON representation by using the method %ToJSON()
and the opposite action - %FromJSON()
. There is also a possibility to serialize and deserialize JSON enabled classes to strings and streams if there's a need to do it.</p>
This concludes this very brief tutorial about JSON classes and their usage. Hope it helps figure out the best way to do things.
Top comments (0)