Reputation: 987
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?
Upvotes: 4
Views: 1745
Reputation: 2678
Yeah.It's simple.Try below solutions
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"}]
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"}]
Upvotes: 3
Reputation: 3892
Well if you want the result to be in key-value
pair you can take advantage of HQL
query
def query = """select new map(u.username as username, u.lastUpdated as lastUpdated) from User u where status < 2"""
def result = User.executeQuery(query)
println (result as JSON)
This will give you the output as below
[{"username": "user1", "lastUpdated":"2016-09-21 06:49:46"}, {"username": "user2", "lastUpdated":"2016-09-22 11:24:42"}]
Upvotes: 1
Reputation: 2784
You are looking for Grails projections.
def result = Person.createCriteria().list {
lt("status", 2)
projections {
property('username')
property('lastUpdated')
}
} as JSON
Upvotes: 2