我是grails的新手,想要学习,在这段代码中我创建了jsonDate并在create方法中使用。当我从SoapUi发送数据时,我收到的错误如Cannot cast object '13/01/2014' with class 'java.lang.String' to class 'java.util.Date'
。
class RequestMainController {
static scaffold = true
static allowedMethods = [save: "POST", updat``e: "PUT", delete: "DELETE"]
def index(Integer max) {
params.max = Math.min(max ?: 10, 100)
respond RequestMain.list(params), model:[requestMainInstanceCount: RequestMain.count()]
}
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
//System.out.println(Current Date + sdf.format(new Date());
String mydate = "01-08-2011";
Date parseDate = sdf.parse(mydate);
def slurper = new JsonSlurper()
def requestMain = slurper.parseText('{"milestoneSequenceNumber":"111","recordStartDate":"13/01/2014",
"recordEndDate":"13/01/2014","application":"app","applicationType":"A""}');
def create(){
//def jsonObject = grails.converters.JSON.parse(requestMain)
def milestoneSequenceNumber = requestMain.milestoneSequenceNumber
def recStartDate = requestMain.recordStartDate
def recEndDate = requestMain.recordEndDate
def application = requestMain.application
def applicationType = requestMain.applicationType
System.out.println(" MILESTONE_SEQ_NO = $milestoneSequenceNumber,REC_START_DATE = $recStartDate, REC_START_DATE=$recEndDate,APPLICATION=$application,APPL_TYPE=$applicationType)
render(view:"create", action:"save")
}
def save() {
RequestMain requestMain1 = new RequestMain()
requestMain1.mimeNo = requestMain.milestoneSequenceNumber
requestMain1.recStartDate = requestMain.recordStartDate
requestMain1.recEndDate = requestMain.recordEndDate
requestMain1.application = requestMain.application
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
String mydate = "01-08-2011";
Date parseDate = sdf.parse(mydate);
requestMain1.save()
render "Success!"
}
}
答案 0 :(得分:3)
实际上你在里面的错误是在线保存 -
Date parseDate = sdf.parse(mydate);
是因为您无法将日期字符串直接更改为SimpleDateFormat。因此,您需要将其更改为Date类对象。
String mydate = "01-08-2011";
def parsedDate = Date.parse("yyyy-MM-dd", mydate);
Date parseDate = sdf.parse(parsedDate);
虽然这样做也是不合逻辑的,因为parsedDate已经是Date类的对象,所以你不需要再转换它。
如果您因任何特定原因未使用SimpleDateFormat,则可以始终使用以下方法 -
将日期更改为特定格式的字符串 -
def myStringDate = dateObj.format("yyyy-MM-dd");
将字符串更改为日期
def myDate = Date.parse("yyyy-MM-dd", myStringDate);
这些方法更具GROOVYish,让您的工作变得轻松。
这些传递的日期格式可以使用java documentation- http://docs.oracle.com/javase/1.5.0/docs/api/java/text/SimpleDateFormat.html
中指定的格式进行答案 1 :(得分:1)
假设您在尝试从创建视图中保存后收到此错误,您似乎忘记在java.lang.Date
方法中将字符串转换为save()
。在分配到requestMain1
属性之前,请将它们转换为java.lang.Date
:
def save() {
RequestMain requestMain1 = new RequestMain()
requestMain1.mimeNo = requestMain.milestoneSequenceNumber
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
requestMain1.recStartDate = dateFormat.parse(requestMain.recordStartDate)
requestMain1.recEndDate = dateFormat.parse(requestMain.recordEndDate)
(...etc...)
}