Extracting array from JSON in mule esb

自古美人都是妖i 提交于 2019-12-01 11:19:13

There best way to query json is to transform it to a Map.

<json:json-to-object-transformer returnClass="java.util.HashMap" />

And then query it using MEL like standard MVEL or Java syntax

<logger message="#[payload.People[0].Details.email]" level="INFO" />

If you want to keep the original json payload intact, you can store the map in a variable using an enricher:

<enricher target="#[flowVars.myJsonMap]">
   <json:json-to-object-transformer returnClass="java.util.HashMap" />
</enricher>

And query the variable instead of the payload:

<logger message="#[flowVars.myJsonMap.People[0].Details.email]" level="INFO" />

You could also map the json to a custom class using Jackson and change the returnClass attribute to your class.

This MEL cheat sheet detail JSON processing with MEL and also how to handle Maps, arrays etc: http://www.mulesoft.org/documentation/display/current/MEL+Cheat+Sheet

Note: You may come across a #[json:] evaluator, but this is deprecated in favour of the approach above.

UPDATE:

If you want to grab all the emails at once you can use MVEL projections:

<enricher target="#[flowVars.myJsonMap]" source="#[(Details.email in payload.People)]">
       <json:json-to-object-transformer returnClass="java.util.HashMap" />

    </enricher>

Mvel projections: http://mvel.codehaus.org/MVEL+2.0+Projections+and+Folds

If you want to get the particular email in the details use the below MEL expression.

#[json:People[0]/Details/Email]

If you want to get all the emails, pass the json path of repeatable in ForEach Collections then pass the path to get Email as shown below.

 <flow name="parsingjsonFlow">
    <http:listener config-ref="HTTP_Listener_Configuration" path="/" doc:name="HTTP"/>
    <foreach collection="#[json:People]" doc:name="For Each">
        <logger message="#[json:/Details/Email]" level="INFO" doc:name="Logger"/>
    </foreach>
    <catch-exception-strategy doc:name="Catch Exception Strategy">
        <logger message="#[exception.getClass()]" level="INFO" doc:name="Logger"/>
    </catch-exception-strategy>
</flow>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!