Search code examples
javagrailsgrails-ormrendergrails-domain-class

How to exclude some fields when listing Grails domain?


I'm wondering how can I list Grails domain and exclude some fields at same time. I'm guessing solution must be simple but I just can not see it.

I prepared some example with domain User:

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

    static constraints = { }  

    static mapping = { }
}

At this point I want to list all users which have status below 2.

render User.findAllByStatusLessThen(2) as JSON

I want to render JSON response to clientside without some fields. For example I just want to render users with fields username and lastUpdated so rendered JSON would look like this:

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

What's the easiest way to achieve that?


Solution

  • Yeah.It's simple.Try below solutions

    1. Solution 1

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

    output

       [{"user1", "2016-09-21 06:49:46"}, {"user2", "2016-09-22 11:24:42"}]
    
    1. Solution 2 - using this you will get output in the Key-Value pair

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

    output

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