首页 > 解决方案 > Grails 4:自定义域模型编组器在 Grails 4 上不起作用

问题描述

我目前的问题是我创建的自定义对象编组器,因为 grails 2.4.5到 grails 3.3.0不适用于 grails 4.0.0。Grails 4 默认响应域模型而不是我创建的自定义。

以下是我拥有的代码。请查看,如果您发现有问题,请让我知道伙计们,如果您能帮助我,我将很高兴。


ResponseSender.groovy

package com.problem.solve.common

import org.springframework.http.HttpStatus

trait ResponseSender {

    void sendResponse() {
        render status: HttpStatus.NO_CONTENT
    }

    void sendResponse(def responseData) {
        respond (responseData)
    }

    void sendResponse(HttpStatus status, def responseData) {
        response.status = status.value()
        respond (responseData)
    }
}

ResponseSender.groovy特征在控制器上实现。


MarshallerInitializer.groovy

package com.problem.solve.marshaller

class MarshallerInitializer {

    CustomObjectMarshallers customObjectMarshallers

    void initialize() {
        customObjectMarshallers.register()
    }
}

这个MarshallerInitializer.groovy将在 bootstrap 初始化时被调用。

package com.problem.solve.marshaller

class CustomObjectMarshallers {

    List marshallers = []

    void register() {
        marshallers.each {
            it.register()
        }
    }
}

这个CustomObjectMarshallers.groovy将注册所有编组器。


UserMarshaller.groovy

package com.problem.solve.marshaller.marshalls

import com.problem.solve.security.User
import grails.converters.JSON

class UserMarshaller {
    void register() {
        JSON.registerObjectMarshaller(User) { User user ->
            return [
                    id: user.id,
                    fullName: user.fullName,
                    username: user.username,
                    emailAddress: user.emailAddress,
                    roles: user.authorities.authority,
                    dateCreated: user.dateCreated,
                    lastUpdated: user.lastUpdated,
                    _entityType: 'User'
            ]
        }
    }

这个UserMarshaller.groovy是一个示例域模型,我想将它从域模型转换为 json 响应。


资源.groovy

import com.problem.solve.marshaller.CustomObjectMarshallers
import com.problem.solve.marshaller.MarshallerInitializer
import com.problem.solve.marshaller.marshalls.*

// Place your Spring DSL code here
beans = {
    customObjectMarshallers(CustomObjectMarshallers) {
        marshallers = [
                new UserMarshaller()
        ]
    }

    marshallerInitializer(MarshallerInitializer) {
        customObjectMarshallers = ref('customObjectMarshallers')
    }
}

此设置的问题不适用于 grails 4,但此设置适用于 grails 2.4.5 和 grails 3.3.0。

我真的需要你们的帮助。

太感谢了 :)

标签: grailsgroovy

解决方案


我通过创建 DomainModelResponseDto 作为响应域模型来解决这个编组器问题。

例子:

class UserResponseDto {
    String id
    String username
    String email

    UserResponseDto(User user) {
        id = user.id
        username = user.username
        email = user.email
    }
}

推荐阅读