javajsonapache-camelspring-dsl

How can I iterate over a nested list inside Camel body?


I am trying to access data in the incoming {body} of my incoming Json I have done the unmarshaling with Jackson and mapped it to a Java Map Class with

  `.unmarshal().json(JsonLibrary.Jackson, java.util.Map.class)
`

My incoming Json data is something like this after unmarshal step above

{ "projectId" : 12345,
"title" : “12345 - Plant 1 Processing",
"partners": [{"partnerName": "partnerJV1", "partnerLocation": "JA"},
{"partnerName": "partnerJV2", "partnerLocation": "FL"},
{"partnerName": "partnerJV3", "partnerLocation": "OH"}
]

The partners field can have 0-N number of partnerName, partnerLocation maps.

Now I am inserting this into a SQL table with

.to("sql:classpath:sql/sql_queries.sql")

My sql_queries.sql has the following query in it to insert data fields into the table:

INSERT INTO MY_TABLE(PID, TITLE, PartnerName1, PartnerLocation1, PartnerName2, PartnerLocation2, PartnerName3, PartnerLocation3) VALUES(:#${body['projectId']}, :#${body['title']}, :#${body['partners[0]']['partnerName']}, :#${body['partners[0]']['partnerLocation']} )

my problem is I cannot know the exact number of partners and without it I cannot write my SQL statement. I get IndexOutOfBounds exception if I access say :#${body['partners'][2]['partnerName']}

But there is only one partners in the incoming body.

So how can I in camel iterate over the nested map inside my JSON based on it's length and initialize my PartnerName, PartnerLocation fields for my insert statement?


Solution

  • Try like this:

                .setProperty("projectId", simple("body['projectId']"))
                .setProperty("title", simple("body['title']"))
                .setBody(simple("body['partners']"))
                .split(simple("body"))
                .process{//prepare your properties here}
                .end()
                .to("sql:classpath:sql/sql_queries.sql");
    

    And sql will look like this:

    INSERT INTO MY_TABLE(PID, TITLE, PartnerName1, PartnerLocation1, PartnerName2, PartnerLocation2, PartnerName3, PartnerLocation3) VALUES(:#${exchangeProperty.projectId}, :#${exchangeProperty.title}, :#${exchangeProperty.partnerName1}, :#${exchangeProperty.partnerLocation1} , :#${exchangeProperty.partnerName2}, :#${exchangeProperty.partnerLocation2}, :#${exchangeProperty.partnerName3}, :#${exchangeProperty.partnerLocation3}   )
    

    UPD: for all data in 1 row