質問

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)
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top