我正在尝试将请求绑定到命令对象。我必须在命令对象中映射一个集合,但我收到错误“类型不匹配,拒绝值null”。我被困在这里,我怎么能解决这个问题。
我的命令对象是
@Validateable
public class CreateFundingCommand extends BaseCommand {
Set<Causes>
}
我的域类是
class CrowdFunding extends BaseEntity{
Set<Causes>
}
我的控制器是
def saveCreateFunding(CreateFundingCommand createFundingCommand){
log.debug"hello"+params
createFundingCommand.validate()
if(createFundingCommand.hasErrors()){
log.debugg"errors"+createFundingCommand.errors
}else{
crowdFundingService.saveCreateFunding(createFundingCommand.getCrowdFunding())
}
}
原因类是
class Causes extends BaseEntity {
String name
String description
String icon
}
我的参数是:
causes:{"name":"prabh","description":"ggg","icon":"deec"}
错误是:
rejected value [{"name":"prabh","description":"ggg","icon":"deec"}]; codes [com.volcare.command.crowdFunding.CreateFundingCommand.causes.typeMismatch.error,com.volcare.command.crowdFunding.CreateFundingCommand.causes.typeMismatch,createFundingCommand.causes.typeMismatch.error,createFundingCommand.causes.typeMismatch,typeMismatch.com.volcare.command.crowdFunding.CreateFundingCommand.causes,typeMismatch.causes,typeMismatch.java.util.Set,typeMismatch]; arguments [causes]; default message [Could not find matching constructor for: com.volcare.domain.setting.Causes(java.lang.String)]
答案 0 :(得分:1)
问题可能如下:
causes:{"name":"prabh","description":"ggg","icon":"deec"}
你可能希望它是这样的:
causes:[{"name":"prabh","description":"ggg","icon":"deec"}]
请注意,causes
的值应该是Map的列表,而不是Map。
见https://github.com/jeffbrown/fundbinding。该项目包括以下内容:
的src /常规/演示/ CreateFundingCommand.groovy
package demo
@grails.validation.Validateable
class CreateFundingCommand extends BaseCommand {
Set<Cause> causes
}
的grails-app /控制器/演示/ DemoController.groovy
package demo
class DemoController {
def saveCreateFunding(CreateFundingCommand createFundingCommand){
if(createFundingCommand.hasErrors()){
render 'Errors were found'
}else{
render 'No errors were found'
}
}
}
测试/单元/演示/ DemoControllerSpec.groovy
package demo
import grails.test.mixin.TestFor
import spock.lang.Specification
@TestFor(DemoController)
class DemoControllerSpec extends Specification {
void "test valid command object"() {
when:
request.json = '{"causes":[{"name":"prabh","description":"ggg","icon":"deec"}]}'
controller.saveCreateFunding()
then:
response.text == 'No errors were found'
}
void "test invalid command object"() {
when:
request.json = '{"causes":{"name":"prabh","description":"ggg","icon":"deec"}}'
controller.saveCreateFunding()
then:
response.text == 'Errors were found'
}
}
另请注意,在您的代码中,您在控制器操作中调用了createFundingCommand.validate()
,这是不必要的。在代码执行之前,该实例已经过验证。
我希望有所帮助。