【问题标题】:mule - mapping array or object JSON responsemule - 映射数组或对象 JSON 响应
【发布时间】:2018-03-13 18:33:49
【问题描述】:

我调用一个 web 服务,如果成功则返回一个 json 数组:

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

如果失败,它会返回一个对象:

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

如何映射两个响应以处理它们?

【问题讨论】:

    标签: java json mapping mule


    【解决方案1】:

    您可以根据 Web 服务响应代码使用不同的转换。

    类似这样的:

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

    【讨论】:

      【解决方案2】:

      你可以使用

      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
      

      【讨论】:

      • 不,它不起作用。它给出了以下异常:org.codehaus.jettison.json.JSONException:JSONObject 文本必须在 [ 的字符 1 处以“{”开头
      【解决方案3】:

      在 HTTP 之后使用下面的转换消息,您将获得正确的输出..

      %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
      }
      

      在此之后你的输出将是

      1.成功案例

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

      2.失败案例

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

      【讨论】:

        猜你喜欢
        • 2021-12-03
        • 1970-01-01
        • 2020-07-09
        • 1970-01-01
        • 1970-01-01
        • 2019-09-30
        • 1970-01-01
        • 2017-11-03
        • 2019-09-24
        相关资源
        最近更新 更多