Override property name to generate a JSON message
Hi community!
Does anyone know if it´s possible to override a property name to generate a JSON message based on the instance of object?
Thanks,
José Sampaio
Discussion (2)0
Comments
Assuming this is on 2016.2 you could override the %ToJSONValue method which is used to generate the JSON.
Here's a sample, using %ToDynamicObject (2016.2+):
Class DC.CustomJSONSample extends %RegisteredObject
{
Property myProperty As %String [ InitialExpression = "hello" ];
Property other As %String [ InitialExpression = "world" ];
/// Rename myProperty to custom_property_name
Method %ToDynamicObject(target As %Object = "", ignoreUnknown = 0) [ ServerOnly = 1 ]
{
Do ##super(.target,.ignoreUnknown)
Do target.$set("custom_property_name",target.myProperty,target.$getTypeOf("myProperty"))
Do target.$remove("myProperty")
}
ClassMethod Run()
{
Set tObj = ..%New()
Write tObj.$toJSON()
}
}Output:
SAMPLES>d ##class(DC.CustomJSONSample).Run()
{"other":"world","custom_property_name":"hello"}For other discussions with solutions/examples involving %ToDynamicObject, see:
https://community.intersystems.com/post/json-cache-and-datetime
https://community.intersystems.com/post/create-dynamic-object-object-id