检查mule中的json密钥或对象属性

时间:2015-02-27 20:10:08

标签: json object mule mule-studio

场景 - 我必须遍历此有效负载,对于那些有错误的列表,我需要增加计数。但是如何检查错误属性是否存在?

{
    "jobGuid": "123",
    "status": "COMPLETED",
    "listings": [
        {
            "exteralListingId": 7654320
        },
        {
            "exteralListingId": 7654321,
            "error": {
                "code": "inventory.listings.sellerCreditCardNotfound",
                "description": "Seller credit card not found"
            }
        }
    ]
}

选项1 - 使用json语法检查
Option2 - 迭代列表中的for-each循环,检查#[payload.error!= null]。但它给出了错误 - 消息有效负载的类型为:LinkedHashMap

1 个答案:

答案 0 :(得分:1)

您可以使用类似xpath的jsonPath,但是对于JSON

我用json提供了我的例子。如您所见,#[json:listings]返回数组,此数组将由foreach迭代,然后使用#[json:error]验证是否包含错误标记。 errorCount变量存储错误的数量,它将在控制台中打印出来。

<http:listener-config name="HTTP_Listener_Configuration" host="0.0.0.0" port="8081" doc:name="HTTP Listener Configuration"/>
    <flow name="demoFlow">
        <http:listener config-ref="HTTP_Listener_Configuration" path="/" doc:name="HTTP"/>
        <set-payload value="{&quot;jobGuid&quot;:&quot;123&quot;,&quot;status&quot;:&quot;COMPLETED&quot;,&quot;listings&quot;:[{&quot;exteralListingId&quot;:7654320},{&quot;exteralListingId&quot;:7654321,&quot;error&quot;:{&quot;code&quot;:&quot;inventory.listings.sellerCreditCardNotfound&quot;,&quot;description&quot;:&quot;Seller credit card not found&quot;}},{&quot;exteralListingId&quot;:7654321,&quot;error&quot;:{&quot;code&quot;:&quot;inventory.listings.sellerCreditCardNotfound&quot;,&quot;description&quot;:&quot;Seller credit card not found&quot;}},{&quot;exteralListingId&quot;:7654321,&quot;error&quot;:{&quot;code&quot;:&quot;inventory.listings.sellerCreditCardNotfound&quot;,&quot;description&quot;:&quot;Seller credit card not found&quot;}}]}" doc:name="Set Payload"/>     
        <expression-transformer expression="#[json:listings]" doc:name="Expression"/>
        <set-variable variableName="errorCount" value="#[0]" doc:name="Variable"/>
        <foreach collection="#[message.payload]" doc:name="For Each">
            <expression-filter expression="#[json:error]" doc:name="Expression"/>
            <set-variable variableName="errorCount" value="#[flowVars.errorCount + 1 ]" doc:name="Variable"/>
            <logger message="counter: #[errorCount]" level="INFO" doc:name="Logger"/>
        </foreach>
    </flow>

有关更多信息,请查看mule的官方文档。 http://www.mulesoft.org/documentation/display/current/JSON+Module+Reference