Generic Class in COS
Hello everyone,
I'm doing a REST service for integration between 2 systems. The system that invokes me expects a response object where only one of its attributes changes. It could be something like this:
Class ResponseCustomer { Property Code As %String; Property Info As Customer; }
Class ResponseAppointment { Property Code As %String; Property Info As Appointment; }
Class ResponseCancellation { Property Code As %String; Property Info As %String; }
To avoid creating almost identical objects for each of the methods of my REST service, I had thought to implement it with generic classes known in other languages like .NET or JAVA that allow to be able to define at run time the type of that parameter. In addition, that response must be able to be transformed into JSON. I imagine something like this (in pseudo code / COS / .NET):
Class Response <T> { Property Code As %String; Property Info As T; }
// Create an answer to create a new Customer Set responseCustomer = ## class (Response <Customer>). New () // Create an answer to reserve a room Set responseAppointment = ## class (Response <Appointment>).% New () // Create an answer to cancel a reservation Set responseCancelation = ## class (Response <String>).% New ()
Is this possible in COS?. I haven't found a similar question about this in the community.
My attempts have been with the use of %Library.DynamicObject but when creating the JSON, the dynamic part isn't serialized.
Thanks
Hi Javier,
COS does not have a Generics implementation, mainly as its a loosely/duck typed language.
You can however write generic code without needing Generics.
Make your property a base class of your Info classes, this can be %RegisteredObject...
Property Code As %String;
Property Info As %RegisteredObject;
}
You can now assign any valid object to that property at run time.
You won't be able to assign a string to this property, so create a class with a single property of type string that you can assign it to.
Try that and if you get stuck with the JSON serialisation then post back the code that is not working.
Sean.
Thanks Sean,
With %RegisteredObject occurring same as with %Library.DynamicObject, the dynamic attribute is not serialized.
The REST service architecture is a BusinessService that invokes a BusinessOperation. In this BO I have a block "code" that does the following:
Return to the BS, I perform the serialization with class:
and return the result with:
The result of invoking the REST service from POSTMAN or SOAPUI is this:
From the terminal this is the result
In order to provide some detail, this is the definition of the classes involved:
I thank your contribution because I am confused.
You can use the class %ZEN.proxyObject, e.g.: