用于检查 json 文件的 mule 表达式

mule expression for checking json file

是否可以编写一个 mule 表达式来检查以下 json 请求中的所有 Name 值是否相同?

我正在尝试类似 #[($ in message.payload.id.items if $.Name==$.Name)] 但它不起作用 请推荐

{"id":
    {
     "items" : [
    {
    "Name": "Raj",
    "transaction_tag": "value1",
    "transaction_type": "withdraw"
    },
{
    "Name": "Raj",
    "transaction_tag": "value2",
    "transaction_type": "submit"
    },
  {
    "Name": "Raj",
    "transaction_tag": "value3",
    "transaction_type": "inquiry"
    }
]
}
}

您可以使用以下代码检查所有 Name 元素是否具有相同的值='Raj':-

<http:listener-config name="HTTP_Listener_Configuration" host="0.0.0.0" port="8081" doc:name="HTTP Listener Configuration"/>

 <flow name="testFlow">
    <http:listener config-ref="HTTP_Listener_Configuration" path="/" doc:name="HTTP"/>
    <json:json-to-object-transformer returnClass="java.util.HashMap" doc:name="JSON to Object"/>
        <foreach collection="#[message.payload.id.items]" doc:name="For Each">
                <choice doc:name="Choice">
                    <when expression="#[message.payload.Name=='Raj']">
                        <logger level="INFO" doc:name="Logger" message="Equal values"/>
                    </when>
                 <otherwise>
                        <logger message="Not equal" level="INFO" doc:name="Logger"/>
                    </otherwise>
                </choice>
         </foreach>
         <json:object-to-json-transformer doc:name="Object to JSON"/>
    </flow>

替代选项:-
如果您知道 JSON 列表中元素的数量将是固定的(例如在本例中为 3 个 Name 元素),您可以尝试以下操作:-

 <choice doc:name="Choice">
    <when expression="#[message.payload.id.items[0].Name==message.payload.id.items[1].Name and message.payload.id.items[1].Name==message.payload.id.items[2].Name and message.payload.id.items[2].Name==message.payload.id.items[0].Name]">
        <logger level="INFO" doc:name="Logger" message="Equal"/>
      </when>
      <otherwise>
         <logger message="Not equal" level="INFO" doc:name="Logger"/>
       </otherwise>
  </choice>

但最好的选择是遵循上述解决方案,这对任何数量的元素都有好处

我认为更清晰的实现是使用 JSON 到对象转换器将 JSON 映射到 POJO(Java 对象)。

例如:

<json:json-to-object-transformer returnClass="com.mycompany.Request" doc:name="JSON to Request"
            doc:description="Convert the JSON payload to a Java object for further processing." />

您可以将您的 POJO "Request," 命名为上面的示例,并作为项目列表的成员,以及名称为 hasRepeatedItems() 的布尔方法 returns true 或 false 如果项目是否重复。

在你的 JSON 通过你的转换器(成功)之后,你的有效负载现在将是一个 Java 对象 "Request."

您可以使用选择路由器并调用方法 payload.hasRepeatedItems()。

<choice doc:name="Choice">
            <when expression="payload.hasRepeatedItems()">
                Do something ...
            </when>
            <otherwise>
                Do something else...
            </otherwise>
</choice>

希望对您有所帮助。如果需要进一步说明,请让我打结。

@Anirban..对于每个循环解决方案都很棒..但是它的硬编码名称你必须再次检查整个数组的所有名称并从中计算。