JSON
1、什么是JSON
JSON(JavaScript Object Notation, JS 对象标记) 是一种轻量级的数据交换格式,目前使用特别广泛。
在后端可以把json理解为Stirng字符串的另一种表达方式
{"name": "QinJiang"}
{"age": "3"}
{"sex": "男"}
这就是一种json字符串表达形式,它代表一个类,name、age、sex是他的三种属性
2、如何给前端传递一个JSON
-
导入json包
<dependencies> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.10.2</version> </dependency> </dependencies>
-
在Controller中创建方法:
@RequestMapping("/j1") public String getJson() throws JsonProcessingException { ObjectMapper objectMapper = new ObjectMapper(); User user = new User("张三",13,"男"); String s = objectMapper.writeValueAsString(user); return s; }
@RequestMapping("/j2")
public String getJson2() throws JsonProcessingException {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
objectMapper.setDateFormat(sdf);
String s = objectMapper.writeValueAsString(date);
return s;
}
这两个方法里s即代表返回的json字符串
第二个方法中我们想要返回的是date日期类型的数据
但是使用date类型的数据直接返回前端会显示一个时间戳,并不是正常的日期类型
我们需要通过SimpleDateFormat来修改显示格式
objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false); 表示不使用时间戳描述日期
objectMapper.setDateFormat(sdf);表示使用sdf格式来描述日期
由于我们需要在很多个方法中使用到JSON字符串,可以把他的方法封装为一个java工具类
public class JsonUtils {
public static String getJson(Object object){
return getJson(object,"yyyy-MM-dd HH:ss");
}
public static String getJson(Object object,String dateFormat){
ObjectMapper objectMapper = new ObjectMapper();
SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
objectMapper.setDateFormat(sdf);
try {
return objectMapper.writeValueAsString(object);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return null;
}
}
创建该工具类后,我们就可以调用其进行简便的返回JSON
@RequestMapping("/j1")
public String getJson() throws JsonProcessingException {
User user = new User("张三",13,"男");
return JsonUtils.getJson(user);
}
@RequestMapping("/j2")
public String getJson2() throws JsonProcessingException {
Date date = new Date();
String d = "yyyy-MM-dd HH:mm:ss";
return JsonUtils.getJson(date,d);
}