Parse JSON in Mule 3.2 Flow

2019-06-09 00:44发布

问题:

If I have the following JSON

[ 
  { "category": "reference",
    "author": "Nigel Rees",
    "title": "Sayings of the Century",
    "price": 8.95
  },
  { "category": "fiction",
    "author": "Evelyn Waugh",
    "title": "Sword of Honour",
    "price": 12.99
  },
  { "category": "fiction",
    "author": "Herman Melville",
    "title": "Moby Dick",
    "isbn": "0-553-21311-3",
    "price": 8.99
  },
  { "category": "fiction",
    "author": "J. R. R. Tolkien",
    "title": "The Lord of the Rings",
    "isbn": "0-395-19395-8",
    "price": 22.99
  }
]

I can get the price of "Moby Dick" using the following JSONPath:

$..[?(@.title=='Moby Dick')].price

RESULT:

'0' => "8.99"

BUT how do I do this in Mule..... what would the json expression look like to get the same result within a mule 3.2 flow?

I don't mind if your answer shows how to do it another way as long as I get the same result within mule.

Can anyone please help me with this??

回答1:

The way to do that with MEL is to deserialize the JSON payload and use an MVEL filtered projection:

<json:json-to-object-transformer returnClass="java.util.List" />
<expression-transformer 
    expression="#[($.price in message.payload if $.title == 'Moby Dick')[0]]" />

This expression doesn't take into account cases when Moby Dick isn't present. You didn't mention what to do in that case: I can beef up the expression if you specify the desired behavior when the book's not found.