如何在 Camunda 的 Javascript 脚本任务中使用序列化变量

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

考虑使用这样的过程变量:

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

我正在尝试在脚本任务中编写一个 Javascript,它提取一个变量,如上所示,并使用它。这是我的进展:

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);

但是当我运行这个时,它会抛出以下错误:

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>

在这种情况下,ArrayList's reference 说它有 sizeadd 两个!。怎么回事?

检查您正在呼叫的 Camunda API:
VariableScope#getVariableTyped (DelegateExecution implements VariableScope). This method returns an instance of TypedValue

使用 execution.getVariableTyped("arr", true).getValue();execution.getVariable("arr"); 访问实际的 ArrayList。