简体   繁体   中英

Collect closure in groovy

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?

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

You can try it-

List<JSON> personsListJson = JSON.parse(personJsonText);
persons = personsListJson.collect{
    new Person(id:it.id, firstname:it.firstname, lastname:it.lastname)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM