gpt4 book ai didi

java - 如何在列出 Grails 域时排除某些字段?

转载 作者:行者123 更新时间:2023-12-02 13:05:05 25 4
gpt4 key购买 nike

我想知道如何列出 Grails 域并同时排除某些字段。我猜解决方案一定很简单,但我就是看不到它。

我准备了一些带有域用户的示例:

class User implements Serializable {
String username
String email
Date lastUpdated
String password
Integer status

static constraints = { }

static mapping = { }
}

此时我想列出状态低于 2 的所有用户。

render User.findAllByStatusLessThen(2) as JSON

我想向客户端呈现 JSON 响应,而不需要某些字段。例如,我只想使用字段 usernamelastUpdated 呈现用户,因此呈现的 JSON 如下所示:

[{"username": "user1", "lastUpdated":"2016-09-21 06:49:46"}, {"username": "user2", "lastUpdated":"2016-09-22 11:24:42"}]

实现这一目标的最简单方法是什么?

最佳答案

是的。很简单。尝试以下解决方案

  1. 解决方案1

    List userList = User.where{ status < 2 }.property("username").property("lastUpdated").list()

    render userList as JSON

输出

   [{"user1", "2016-09-21 06:49:46"}, {"user2", "2016-09-22 11:24:42"}]
  • 解决方案 2 - 使用此方法,您将获得 Key-Value 对中的输出

    List userList = User.findAllByStatusLessThen(2)?.collect{
    [username : it.username, lastUpdated: it.lastUpdated]}

    render userList as JSON
  • 输出

        [{"username": "user1", "lastUpdated":"2016-09-21 06:49:46"}, {"username": "user2", "lastUpdated":"2016-09-22 11:24:42"}]

    关于java - 如何在列出 Grails 域时排除某些字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39654465/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com