mrboieng
mrboieng

Reputation: 346

mule - mapping array or object JSON response

I call a web service that returns a json array in case of success:

[
  {"name":"a"},
  {"name":"b"}
]

And in case of failure, it returns an object:

{
 "status":"Failed",
 "describtion":"Error occured"
}

How to map both response in order to handle them?

Upvotes: 0

Views: 153

Answers (3)

Swapnil Udamale
Swapnil Udamale

Reputation: 61

Use below Transform Message after HTTP you will get proper output..

%dw 1.0
%output application/json
---
{
    Status:"Success" when payload.status != 'Failed' otherwise "Failure",
    Describtion:payload.describtion when payload.status == 'Failed' otherwise null,
    Data:payload when payload.status != 'Failed' otherwise null
}

After this your Output will be

1.Success case

{
    "Status": "Success",
    "Describtion": null,
    "Data": [
        {
            "name": "a"
        },
        {
            "name": "b"
        }
    ]
}

2.Failure Case

{
    "Status": "Failure",
    "Describtion": "Error occured",
    "Data": null
}

Upvotes: 0

arch-jn
arch-jn

Reputation: 76

You can use different transformation based on the web service response code.

Something like this:

<choice> 
  <when expression="#[message.inboundProperties['http.status'] == 200]">
    <!-- transform success response -->
  </when>
  <otherwise>
    <!-- transform failure response -->
  </otherwise>
</choice>

Upvotes: 1

Muthu
Muthu

Reputation: 158

You can use

JSONObject json = new JSONObject(yourdata);
String statistics = json.getString("status");

if(status == null){
// Show error message
}else{
  String statistics = json.getString("name");
 }

 Try this. Let me know if it not work. I'll give another solution

Upvotes: 0

Related Questions