gpt4 book ai didi

grails - Grails 4:自定义域模型编码不适用于Grails 4

转载 作者:行者123 更新时间:2023-12-02 14:10:01 27 4
gpt4 key购买 nike

我当前的当前问题是自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 特性在 Controller 上实现。

MarshallerInitializer.groovy
package com.problem.solve.marshaller

class MarshallerInitializer {

CustomObjectMarshallers customObjectMarshallers

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

bootstrap 初始化时,将调用此 MarshallerInitializer.groovy
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响应。

resources.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。

我真的需要你们的帮助。

非常感谢 :)

最佳答案

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

例:

class UserResponseDto {
String id
String username
String email

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

关于grails - Grails 4:自定义域模型编码不适用于Grails 4,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58086191/

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