cancel
Showing results for 
Search instead for 
Did you mean: 
Read only

Hashmap in groovy script

vivekvijay
Participant
0 Likes
4,712

I want to covert the following body into a hashap.

<root>

<person>

<id>0001</id>

<firstname>Jack</firstname>

<lastname>Sparrow</lastname>

</person>

<person>

<id>0002</id>

<firstname>Tony</firstname>

<lastname>Stark</lastname>

</person>

</root>

What are the changes I should be making to the following code?

def Message processData(Message message) {

def body = message.getBody(java.io.Reader);

HashMap<Integer, String> hmap = new HashMap<Integer, String>(); -----> should it be <string , string>??

def Root = new XmlSlurper().parse(body);

Root.person.each{

try{

hmap.put(it.id.text().toString(), it.firstname.text().toString(), it.lastname.text().toString());

}

catch(Exception ex){

//put relevant exception handling here

}

Thanks in advance.

Vivek.

Accepted Solutions (0)

Answers (2)

Answers (2)

MortenWittrock
SAP Mentor
SAP Mentor
0 Likes

Hi Vivek

You pretty much have the pieces you need in the code included in your question.

The core of it should be something like the following:

def people = [:] // Create an empty map
def root = new XmlSlurper().parseText(message.getBody(String)) // Parse the payload

// Now iterate over each <person> element
root.person.each { p ->
    people[p.id.text()] = [firstname: p.firstname.text(), lastname: p.lastname.text()]
}

Here's an article about working with hashmaps in Groovy.

Don't copy random code from strangers on the Internet into your solution without reading and understanding it first 🙂 So please take the time to study it and make it work in your particular iflow.

Regards and have a nice weekend,

Morten

MortenWittrock
SAP Mentor
SAP Mentor
0 Likes

Hi Vivek

A hashmap maps a key to a value, but you are trying to map a key to two values. To do this, create a hashmap, where the key is your ID and the value is another hashmap, mapping the string "firstname" to "Jack" and the string "lastname" to "Sparrow" and so on for all <person> elements.

Regards,

Morten

vivekvijay
Participant
0 Likes

Hi Morten,

Thanks you for the feedback.

I am new to Groovy script , so do you have any reference on how to do the same?

Best Regards,

Vivek.