I'm trying to render a domain with its relationships as JSON in Grails 3.3.8.
I've already rendered a domain called Round
that has many RoundItem
and then I added another domain called AnswerOptions
that belongs to RoundItem
. How can I get that domain attributes from my controller to render all as JSON?
Here's the code:
Round:
class Round {
String name
String comments
Date date
Boolean enable
static hasMany = [items: RoundItem, answers: RoundAnswer]
}
RoundItem:
class RoundItem {
String name
String comments
String image
String type
static belongsTo = [round: Round]
static hasMany = [items: RoundItem, answers: RoundAnswerItem, options: AnswerOption]
}
AnswerOption:
class AnswerOption {
String option
String type
static belongsTo = [item: RoundItem]
}
Method of the controller where domains are rendered:
@Transactional
def round(){
Round round = Round.get(params.id)
RoundItem roundItem = RoundItem.get(params.id)
if(!checkEnableToRound(round)){
render status: METHOD_NOT_ALLOWED, text: '{"message":"Ya han tomado la prueba"}'
return
}
def items = []
round.items.each{
def item = [
id: it.id,
name: it.name,
comments: it.comments,
image: it.image,
answer: ''
]
items.push(item)
}
Student student = springSecurityService.currentUser.student
RoundAnswer answer = RoundAnswer.findByRoundAndGroup(round,student.group)
if(!answer){
answer = new RoundAnswer(
round: round,
group: student.group,
userCreated: student.id,
userUpdated: student.id
)
answer.save(failOnError:true, flush:true)
}
def data = [
id: round.id,
name: round.name,
comments: round.comments,
items: items,
start: answer.dateCreated,
limit: checkLimit(answer.dateCreated)
]
render data as JSON
}
You can use gson plugin to create templates for rendering json output. It's the best practise to do that. More info here: http://views.grails.org/latest/
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.