2013-11-24 49 views
0

我是功能编程范式的新手,希望能够使用groovy学习概念。我有一个包含几个人对象的列表就像一个JSON文本如下:在groovy收集关闭

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

我所试图做它们存储在列表或个人Groovy类的数组如下所示:

class Person { 
    def id 
    String lastname 
    String firstname 
} 

我想用闭包来做到这一点。我试过类似的东西:

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) 
} 

这没有奏效。收集操作是否应该这样做?如果是这样,那我该怎么写呢?

回答

3

尝试

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

而且因为有一个1:JSON和构造函数的参数之间的一对一映射,您可以简化到:

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

但我会保持第一种方法,就好像Json得到了额外的价值(可能超出了你的控制范围),那么第二种方法就会中断

+0

对不起,我当时很蠢。在发布问题之前应该仔细研究一下。非常感谢你的帮助。 – Lee

+0

@Lee不用担心!很高兴我能帮上忙 :-) –

-1

你可以试试看 -

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