jcb
jcb

Reputation: 195

How to I aggregate results into a JSON object through Mule

I am using Mule 3.4, and I have a Mule flow that goes through the line items in a payload, passes each line item to the web service individually, and returns a JSON response for each line item.

What I would like to know is if there is a way in Mule to aggregate those responses into a large JSON object, and return it as a response.

Thanks,

Juan

Upvotes: 0

Views: 1771

Answers (2)

paul
paul

Reputation: 21

While Ryan's for each approach would work (not many good options in my opinion), you better figure out how you want to handle errors if the 2nd web service call for a line item in a 1000 line items throws an exception for whatever reason...

Consult Ryan Carter's other answer to handle that: How to catch exceptions in the Mule foreach scope but keep the process going?

In my use case, my payload was a list of strings where each string was json representing an order. I went with a custom java transformer (wasn't allowed to use groovy in an expression transformer) and just made my json that way. Not the best solution, but seemed the lesser of evils.

Groovy would be something like (Not tested at all):

#[groovy: '{"orders":[' + payload.join(', ') + ']}'] 

Upvotes: 2

Ryan Carter
Ryan Carter

Reputation: 11606

For each item, if you transform the json to a map for example using <json:json-to-object-transformer returnClass="java.util.HashMap" />

This should give you a collection of maps. Then outside of your foreach/loop, convert the list of maps back to json which should give you one json array using: <json:object-to-json-transformer />

For example:

<foreach>
  <!--call service - returns {"id" : "1"} then {"id" : "2"} etc.-->
  <json:json-to-object-transformer returnClass="java.util.HashMap" />`
</foreach>

<json:object-to-json-transformer />

<!-- should output [{"id" : "1"}, {"id" : "2"}] -->

Upvotes: 1

Related Questions