0
votes

I need to look for AccountNo field value in different json payloads. AccountNo can exist at any level in json payload. I need to check if AccountNo exists and then print value in logger.

I am using below enricher but I want to iterate through the Hashmap in mule to check if AccountNo key exists anywhere and then get the value.

Also please suggest if any other way to parse json itself. In xpath "//AccountNo" will look for AccountNo in whole xml document. I am after something similar.

<enricher target="#[flowVars.myJsonMap]" doc:name="Message Enricher"> <json:json-to-object-transformer returnClass="java.util.HashMap" doc:name="JSON to Object"/> </enricher> <logger message="#[flowVars.myJsonMap.employees[0].AccountNo]" level="INFO" doc:name="Logger"/> </flow>

Please find below example json payloads

{
"Account": {
"AccountName": "John",
"AccountNo": "4234324"
 }
 }

{
"Order": {
"OrderId": "34234242",
"ServiceOrder": [
  {
    "AccountNo": "231232",
    "ServiceOrderId": "54654698787"
  },
  {
    "AccountNo": "231232",
    "ServiceOrderId": "78979879797"
  }
  ]
  }
3

3 Answers

0
votes

Since its a hashmap

you can use yourmap.get(keyvalue) to get value.

<logger message="#[flowVars.myJsonMap.yourkey?]" level="INFO" doc:name="Logger"/> 
0
votes

From your question, I assume the following:

  • Your payload contains nested Maps and Lists along with other Objects
  • AccountNo may exists at any level of your payload

You can use a Groovy transformer to recursively parse your payload and collect all existing AccountNo in a List:

//recursively parse any Map or List in myObject
//and store AccountNo objects accountNoList
def parseObject(myObject, accountNoList) {
  if (myObject instanceof java.util.Map) {
    //if Map, check for AccountNo field
    if(myObject.AccountNo != null){
        accountNoList.add(myObject.AccountNo)
    }

    //seek for more AccountNo in Map
    for(e in myObject) {
      parseObject(e.value, accountNoList)
    }
  } else if (myObject instanceof java.lang.Iterable) {
    //if Iterable, parse each values
    for (value in myObject) {
       parseObject(value, accountNoList)
    }
  }
}

myJsonPayload = message.getInvocationProperty('myJsonPayload')
myAccountNoList = [] //init an empty list which will be filled
parseObject(myJsonPayload, myAccountNoList)
return myAccountNoList

Then simply use a Logger.

0
votes

if you are not dealing with large set of json data, just convert the json to XMl using JSONToXMLTransformer and then, use XPATH to look for the data anywhere in the document. This way, you could avoid writing any additional code to parse the json file.