简体   繁体   English

在groovy收集封闭

[英]Collect closure in groovy

I am new to functional programming paradigm and hoping to learn the concepts using groovy. 我是函数式编程范例的新手,希望使用groovy来学习这些概念。 I have a json text containing a list of several person objects like the following: 我有一个json文本,其中包含几个人物对象的列表,如下所示:

{
  "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: 我想要做的是将它们存储在Person groovy类的列表或数组中,如下所示:

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: 由于json和构造函数参数之间存在1:1映射,因此可以将其简化为:

 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 但是我会保留第一种方法,好像Json有一个额外的值(可能超出你的控制)然后第二种方法会破坏

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 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM