我是函数式编程范例的新手,希望使用groovy来学习这些概念。我有一个json文本,其中包含几个人物对象的列表,如下所示:
{
"persons":[
{
"id":1234,
"lastname":"Smith",
"firstname":"John"
},
{
"id":1235,
"lastname":"Lee",
"firstname":"Tommy"
}
]
}
我正在尝试将它们存储在Person 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)
}
这不起作用。收集操作是否应该以这种方式运行?如果是,那我该怎么写呢?
答案 0 :(得分:3)
尝试
personsListJson.persons.collect {
new Person( id:it.id, firstname:it.firstname, lastname:it.lastname )
}
由于json和构造函数参数之间存在1:1的映射,您可以将其简化为:
personsListJson.persons.collect {
new Person( it )
}
但是我会保留第一种方法,好像Json在其中获得了额外的值(可能超出了您的控制范围),然后第二种方法会破坏
答案 1 :(得分:-1)
你可以试试 -
List<JSON> personsListJson = JSON.parse(personJsonText);
persons = personsListJson.collect{
new Person(id:it.id, firstname:it.firstname, lastname:it.lastname)
}