Search code examples
javascriptjavacamundascript-task

How to work with serialized variables in a Javascript Script-Task in Camunda


Consider having a process variable like this:

Object type name: java.util.ArrayList
Serialization Data Format: application/x-java-serialized-object
Value: [{"id": 1, "name": "John"}, {"id": 2, "name": "Jane"]

I'm trying to write a Javascript within a Script-Task which extracts a variable, like above, and works with it. Here's how far I've come:

var arr = execution.getVariableTyped("arr", true);

for (var i=0; arr.size(); i++) {
    var item = arr.get(i);
    //Do somthing with `item`
}
//Add an object to the end of the array
arr.add({ "id": 3, "name": "Jack" });

execution.setVariable("arr", arr);

But when I run this, it throws the following error:

Cannot complete task xxx: Unable to evaluate script: TypeError: ObjectValue [value=[{"id": 1, "name": "John"}, {"id": 2, "name": "Jane"]], isDeserialized=true, serializationDataFormat=application/x-java-serialized-object, objectTypeName=java.util.ArrayList, serializedValue=X chars] has no such function "size" in <eval>

It's in the case that ArrayList's reference says that it's got size and add both!. What's going on?


Solution

  • Check the Camunda API you are calling:
    VariableScope#getVariableTyped (DelegateExecution implements VariableScope). This method returns an instance of TypedValue.

    Use execution.getVariableTyped("arr", true).getValue(); or execution.getVariable("arr"); to access the actual ArrayList.