问题
I have the below json output:
{
"results": [
{
"ID": "1",
"ImageID": "2",
"Name": "Test1",
"Owner": "sysadmin",
"Author": "sysadmin",
"Creator": "sysadmin"
},
{
"ID": "2",
"ImageID": "23",
"Name": "Test2",
"Owner": "sysadmin",
"Author": "sysadmin",
"Creator": "sysadmin"
}
]
}
For each ID in above response, i need to invoke the rest service passing ID as a parameter and the rest service will send me a response back. I have to consolidate all the output into a single json response in mule. I have tried using for each and enricher but could not able to build it. Below is the code which i am using.
<foreach doc:name="For Each Loop">
<logger level="INFO" message="#[payload]" doc:name="Logger" category="INFO"/>
<json:json-to-object-transformer doc:name="JSON to Object"/>
<enricher doc:name="Message Enricher">
<http:request config-ref="SAM" path="/abc/#[payload.ID]" method="GET" doc:name="HTTP"/>
<enrich target="#[flowVars.ID]" source="#[payload[0].ID]"/>
</enricher>
<logger level="INFO" message="#[flowVars.ID]" doc:name="Logger" />
<expression-component doc:name="Expression"><![CDATA[payload.ID = flowVars.ID; ]]></expression-component>
</foreach>
Kindly help me with the way to fix this !!
Thanks
回答1:
You need to initialize an empty array before the for-each loop and add to that array within the for-each:
<set-variable variableName="idList" value="#[[]]" doc:name="Variable - Init idList"/>
<foreach doc:name="For Each Loop">
<logger level="INFO" message="#[payload]" doc:name="Logger" category="INFO"/>
<json:json-to-object-transformer doc:name="JSON to Object"/>
<enricher doc:name="Message Enricher">
<http:request config-ref="SAM" path="/abc/#[payload.ID]" method="GET" doc:name="HTTP"/>
<enrich target="#[flowVars.ID]" source="#[payload[0].ID]"/>
</enricher>
<logger level="INFO" message="#[flowVars.ID]" doc:name="Logger" />
<expression-component doc:name="Expression"><![CDATA[flowVars.idList.add(flowVars.ID);]]></expression-component>
</foreach>
I cover this topic in this video.
回答2:
Thanks Jerney !!
I made it working by doing the following:
<set-variable variableName="outputList" value="#[new java.util.ArrayList()]" doc:name="SetEmptyArray"/>
<foreach collection="json:packshots" doc:name="ForEachDocument">
<set-variable variableName="docName" value="#[json:Name]" doc:name="docName"/>
<http:request config-ref="AH_DAM_API_Configuration" path="${ah.dam.api.get.renditions.path}#[json:Name]" method="GET" doc:name="InvokeAHDamService"/>
<set-payload value="#[xpath3('//*:service/*:document',payload,'NODE')]" doc:name="fetchRenditionInfo"/>
<expression-transformer expression="#[flowVars.outputList.add(payload)]" doc:name="AppendResponseToArray"/>
</foreach>
回答3:
I have used from the savedOutput for array variable.
来源:https://stackoverflow.com/questions/52027993/how-do-you-accumulate-values-within-a-foreach-loop-in-mule