一、问题描述
问题发生场景描述:
1.在实体类Student中定义了一个 入学时间’studentDate’
package com.ihoho.pojo;
import com.alibaba.fastjson.annotation.JSONField;
import java.util.Date;
public class Student {
/**
*学生姓名
*/
private String studentName;
/**
*学生年龄
*/
private int studentAge;
/**
*学生入学时间
*/
private Date studentDate;
public Date getStudentDate() {
return studentDate;
}
public void setStudentDate(Date studentDate) {
this.studentDate = studentDate;
}
}
当我们查询完结果返回到Controller层时 发生如下现象
controller代码:
@CrossOrigin(origins="*") //解决跨域问题 springmvc jar版本要为4.2以上
@RequestMapping(value="/sel")
@ResponseBody
public String select(){
List<Student> list =studentService.selectAll();
System.out.println(JSONArray.toJSONString(list));
return JSONArray.toJSONString(list);
}
前端获取:
<script>
const vm=new Vue({
el:"#app",
data:{
arr:[]
},
mounted(){
//生命周期函数 在渲染完之后执行
let _this=this;
axios.get("http://localhost:8888/studentInfoC/sel").then(function (e) {
_this.arr=e.data;
console.log(_this.arr);
});
}});
</script>
页面结果:
Tomcat控制台输出
问题:如图 不论是后台还是前端接收数据都是一长串数字
二、解决方案
网上提出有两种方案
1.使用JsonFormat注解(PS:由于不是maven项目,且没找到jar包下载所有没有使用此方法)
语法: @JsonFormat(pattern=“yyyy-MM-dd”,timezone = “GMT+8”)
pattern:是你需要转换的时间日期的格式
timezone:是时间设置为东八区,避免时间在转换中有误差
提示:@JsonFormat注解可以在属性的上方,同样可以在属性对应的get方法上,两种方式没有区别
导入maven:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.8.8</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.8.8</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.13</version>
</dependency>
2.@DateTimeFormat 注解
使用方法与JsonFormat注解使用类似
导入maven
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>2.3</version>
</dependency>
使用后没有产生效果,逛博客发现
注解@JsonFormat主要是后台到前台的时间格式的转换
注解@DataFormat主要是前后到后台的时间格式的转换
这时候就不能使用这两种方法了,后面想了一下我使用的阿里巴巴提供的fastjson的json工具,那他们有没有可能提供
然后百度之后发现fastjson有提供一个注解
@JSONField(format=“yyyyMMdd”)
然后我在实体类中的属性上加上了这个注解,最后运行成功,没有出现数字形式
如图:
实体类:
package com.ihoho.pojo;
import com.alibaba.fastjson.annotation.JSONField;
import java.util.Date;
public class Student {
private String studentName;
private int studentAge;
@JSONField(format="yyyy-MM-dd")
private Date studentDate;
@JSONField(format="yyyy-MM-dd")
public Date getStudentDate() {
return studentDate;
}
@JSONField(format="yyyy-MM-dd")
public void setStudentDate(Date studentDate) {
this.studentDate = studentDate;
}
}
本文引用地址:
https://blog.csdn.net/eeeeasy/article/details/81201819 --DataFormat/JsonFormt
https://blog.csdn.net/john1337/article/details/76277617 --fastjson