Master Shifu
Master Shifu

Reputation: 37

How to access values from list of maps in Apache camel message body

Perhaps this is easy, but I am somehow not able to crack it yet. Message body for an exchange is basically a list of maps with both key & value being string. As example,

[{'key'='val1'}, {'key'='val2'},...]

I am using simple expression to set this as a property which I would be using in subsequent routes. This is how I am setting it:

.setProperty("myProperty", simple("${body}"))

But this sets the complete body. I just want to (somehow) set only the values part to avoid setting the entire list of maps. What I have tried and not working so far:

.setProperty("myProperty", simple("${body}['key']"))
.setProperty("myProperty", simple("${body}[*]['key']"))
.setProperty("myProperty", simple("${body}[0]['key']")) // this returns only the first value, I want all

Any idea/suggestion how can I achieve this ?

Upvotes: 1

Views: 4302

Answers (1)

burki
burki

Reputation: 7005

You can access every level of your body with Simple expressions:

${body} // get whole list of maps
${body[0]} // get first map in the list (index 0)
${body[0][key]} // get value of key "key" from the first map in the list 

What you cannot do in a Simple expression is a conversion of your data structure in another one.

However, you can simply plug a Java bean into your route

from("direct:start")
    ...
    .bean(MyConversionBean.class)
    ...;

And do the conversion with Java

public class MyConversionBean {
    public List<String> convertBody() {
        // extract all values (or whatever) with Java;
        return listOfValues;
    }
}

Upvotes: 2

Related Questions