gpt4 book ai didi

json - 如何在Grails中将域及其关系呈现为JSON

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

我正在尝试在Grails 3.3.8中将域及其关系呈现为JSON。

我已经渲染了一个名为Round的域,其中包含许多RoundItem,然后添加了另一个域AnswerOptions,该域属于RoundItem。如何从 Controller 获取该域属性以将其全部呈现为JSON?

这是代码:

回合:

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]
}

呈现域的 Controller 的方法:
@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
}

最佳答案

您可以使用gson插件创建用于呈现json输出的模板。这是最佳做法。
更多信息在这里:http://views.grails.org/latest/

关于json - 如何在Grails中将域及其关系呈现为JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54097656/

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