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

时间:2019-01-08 18:30:49

标签: json grails groovy

我正试图在Grails 3.3.8中将具有关系的域呈现为JSON。

我已经渲染了一个名为Round的域,其中包含许多RoundItem,然后我添加了另一个名为AnswerOptions的域,该域属于RoundItem。如何从控制器获取该域属性以将其全部呈现为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]
}

呈现域的控制器方法:

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

1 个答案:

答案 0 :(得分:0)

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