The Bean contains sql.Date data type, which is stored in json for conversion

Today, I found a problem during the course setting. I threw an exception when passing data to the front end using json.

Cause: there is a course table in my data table. There are two special fields in the middle of the table: start time and end time. The data type of the member used in the corresponding entity class is sql.Date. Mapper interface for data operation has a method to query all courses related to the teacher according to the number of the teacher. I used Json to return data in the Controller layer. The specific implementation is as follows:

     * Get all courses for the current user
     * @return
    @RequestMapping(value="get_crruentUser_course.action",produces= {"html/text;charset=utf-8"})
    public @ResponseBody String getCrruentUserCourse(String crruentUserid) {
        JSONObject result = new JSONObject();
        List<Course> list = null;
        String msg = "";
        Integer code = 0;
        if(crruentUserid==null||crruentUserid=="") {
            msg = "No user information was obtained. Please log in first";
            code = 1;
        }else {
            msg = "User information obtained successfully";
            Integer teacherid = Integer.parseInt(crruentUserid);
            list = courseService.listCourseByTeacherid(teacherid);
        result.put("msg", msg);
        result.put("code", code);
        result.put("coursrList", list);
        return result.toString();

During the service layer test, there was no problem at all. I thought it would be easy to go through it again, but when the integration front-end accesses from the browser side, there was a dramatic error:

Jsonexeption was thrown. This problem is really a bit of a hole. It took me a long time to find out that json does not support sql.Date data when it is converted into a string. I don't want to modify the database. The value can improve the entity class corresponding to the database. The data is transformed on the get methods of starttime and endtime.


    public String getEndtime() {  
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd"); //Format to string is expected to contain The object of data is in json Medium toString Error will be reported in method
        return  df.format(strattime);

    public String getStrattime() {
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        return  df.format(strattime);

Let the two methods return the string, and use the reflection method when json is converted to avoid data exceptions.

Tags: Java JSON SQL Database

Posted on Sat, 30 Nov 2019 23:15:39 -0800 by The voice