groovy中的Collect闭包
我是函数式编程范例的新手,希望使用groovy学习这些概念。我有一个json文本,包含几个person对象的列表,如下所示:groovy中的Collect闭包,groovy,functional-programming,mapreduce,collect,Groovy,Functional Programming,Mapreduce,Collect,我是函数式编程范例的新手,希望使用groovy学习这些概念。我有一个json文本,包含几个person对象的列表,如下所示: { "persons":[ { "id":1234, "lastname":"Smith", "firstname":"John" }, { "id":1235, "lastname":"Lee", "firstname":"Tommy" } ] } class Person {
{
"persons":[
{
"id":1234,
"lastname":"Smith",
"firstname":"John"
},
{
"id":1235,
"lastname":"Lee",
"firstname":"Tommy"
}
]
}
class Person {
def id
String lastname
String firstname
}
我尝试将它们存储在Person groovy类的列表或数组中,如下所示:
{
"persons":[
{
"id":1234,
"lastname":"Smith",
"firstname":"John"
},
{
"id":1235,
"lastname":"Lee",
"firstname":"Tommy"
}
]
}
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)
}
这不管用。collect操作应该这样做吗?如果是这样的话,我该怎么写呢?试试看
personsListJson.persons.collect {
new Person( id:it.id, firstname:it.firstname, lastname:it.lastname )
}
由于json和构造函数参数之间有1:1的映射,您可以将其简化为:
personsListJson.persons.collect {
new Person( it )
}
但是我会保留第一个方法,就好像Json中有一个额外的值(可能超出您的控制),然后第二个方法会中断您可以尝试它-
List<JSON> personsListJson = JSON.parse(personJsonText);
persons = personsListJson.collect{
new Person(id:it.id, firstname:it.firstname, lastname:it.lastname)
}
List personlistjson=JSON.parse(personJsonText);
persons=personsListJson.collect{
新人(id:it.id,firstname:it.firstname,lastname:it.lastname)
}
对不起,我太傻了。在发布问题之前应该仔细看看。非常感谢你的帮助。@Lee别担心!很高兴我能帮忙:-)