Reputation: 155
My Camel route is calling a REST service, which returns a JSON string. Problem is that the JSON is not an object but an array of objects, i.e.:
[
{ object_1 },
{ object_2 }
]
First, I want to figure out if this array is empty, as an expression in a choice-when statement:
.choice()
.when( <array-is-empty-expression> )
...
.otherwise()
...
As a solution I used an expression .when("${body} == '[ ]'") which works fine but it doesn't give me the flexibility to find out how many elements there are in the array (well, just that there are 0 or more than 0). So I would really like something like .when("${body expression} == 0").
Secondly, I want to have an expression that assigns a property of, for example, the second object from the JSON array, to set a header property. For example, .header("To", expression).
Can anyone help me with these expressions?
Upvotes: 1
Views: 3023
Reputation: 3807
The best approach is to unmarshal your Json string to get a list of objects. Then you can invoke size() method to get the number of elements in your list. Finally, you can access any element of the list using [] operator:
from("file://C:/q69164959/test")
.unmarshal().json(JsonLibrary.Jackson)
.setHeader("To", simple("Default"))
.choice()
.when(simple("${body.size()} == 0" ))
.to("log:org.orzowei.so.question.q69164959?level=ERROR")
.otherwise()
.setHeader("To", simple("${body[0][a]}"))
.to("log:org.orzowei.so.question.q69164959?level=WARN")
.end()
.log(LoggingLevel.INFO, "header.To == ${header.To}")
Using [] as input, you can see this log output:
2021-09-13 23:41:49.830 ERROR 32028 --- [/q69076203/test] org.orzowei.so.question.q69164959 : Exchange[ExchangePattern: InOnly, BodyType: java.util.ArrayList, Body: ]
2021-09-13 23:41:49.830 INFO 32028 --- [/q69076203/test] route1 : header.To == Default
Using [{a=1, b=2}, {a=3, b=4}] as input, you can see this log output:
2021-09-13 23:42:01.161 WARN 32028 --- [/q69076203/test] org.orzowei.so.question.q69164959 : Exchange[ExchangePattern: InOnly, BodyType: java.util.ArrayList, Body: [{a=1, b=2}, {a=3, b=4}]]
2021-09-13 23:42:01.161 INFO 32028 --- [/q69076203/test] route1 : header.To == 1
Upvotes: 2