Question

I am new to functional programming paradigm and hoping to learn the concepts using groovy. I have a json text containing a list of several person objects like the following:

{
  "persons":[
   {
     "id":1234,
     "lastname":"Smith",
     "firstname":"John"
   },
   {
     "id":1235,
     "lastname":"Lee",
     "firstname":"Tommy"
   }
  ]
}

What I am trying to do store them in list or array of Person groovy class like the following:

class Person {
    def id
    String lastname
    String firstname
}

I would like to do this using a closure. I tried something like:

def personsListJson= new JsonSlurper().parseText(personJsonText) //personJsonText is raw json string
persons = personsListJson.collect{
   new Person(
       id:it.id, firstname:it.firstname, lastname:it.lastname)
}

This didn't work. Does collect operations supposed to behave this way? If so then how do I write it?

Was it helpful?

Solution

Try

 personsListJson.persons.collect {
     new Person( id:it.id, firstname:it.firstname, lastname:it.lastname )
 }

And as there is a 1:1 mapping between the json and the constructor parameters, you can simplify that to:

 personsListJson.persons.collect {
     new Person( it )
 }

But I'd keep the first method, as if the Json got an extra value in it (maybe out of your control) then the second method would break

OTHER TIPS

You can try it-

List<JSON> personsListJson = JSON.parse(personJsonText);
persons = personsListJson.collect{
    new Person(id:it.id, firstname:it.firstname, lastname:it.lastname)
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top