문제

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