Import mapping a JSON response which can either be a Object or an Array

I have a tricky solution with a app I’m building. The REST API’s which the I’m consuming, sends the response as Array of JSON objects ( if no of objects > 1 ) and sends only a single JSON object ( if no of objects = 1). Consider the example below. If parts are more than 1, then “parts” is received as an Array.  { "response": { "parts": [ { "name": "part 1" }, { "name": "part 2" } ] } }   If there is only 1 part, then “parts“ is received as an object.  { "response": { "parts": { "name": "part 1" } } } How do I handle this situation? How do I create import mapping for such a response?
2 answers

I had a similar problem last week consuming a .NET service from a third party. I came up with two solutions.

Solution one was to use String manipulation to look for the list, and if it wasn’t there to insert it in the right place using a regular expression. I then had a single Input Mapping I could use that would be consistent. String manipulation isn’t really a good idea as it’s very fragile.

Solution two was to have two Input Mappings, one that expects a list and one that doesn’t. If the list failed to import, I could fall back to the version without the list.

Ideally you need your provider to return consistent data.

Hope this helps.


I ended up implementing a Java Action, which intercepts the response received from REST API, makes checks for certain objects which are expected as Array, converts those to arrays if required and then returns modified response back to Micro flow.