Jackson中的注解
springmvc默认会有一套转成json的机制,如果这个机制不符合用户的需求,则可以通过指定的注解进行设置
@RequestBody:加到方法的形参上面,把从前端接收的数据转成json数据
@ResponseBody:加到方法上面,是将后端java对象转为json格式的数据发送给前端。
@JsonProperty("name")//设置格式化成json数据后的属性名称
@JsonInclude(JsonInclude.Include.NON_NULL) // 如果该有该注解的数据属性为null,则不显示
@DateTimeFormat(pattern = "yyyy-MM-dd")//格式化前端传递给后端的时间
@JsonFormat(pattern = "yyyy-MM-dd") //格式化后端传递给前端的时间
@JsonIgnore //显示数据时不显示这个数据
//当json数据出现小数点时,定义一个类JSONDoubleSerializer来序列化该数据
//然后该注解就是让数据在转换成json数据时使用这个序列化的方法
@JsonSerialize(using = JSONDoubleSerializer.class)
JSONDoubleSerializer:
package com.qf.entity;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
/**
* 设置当数据有小数点时保留几位(json数据的序列化)
* @Author kk
* @Date 2020/5/14 15:08
*/
public class JSONDoubleSerializer extends JsonSerializer<Double> {
@Override
public void serialize(Double value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
System.out.println("value = " + value + ", gen = " + gen + ", serializers = " + serializers);
// 1. 把value转换成BigDecimal的类型
BigDecimal bigDecimal = BigDecimal.valueOf(value);
// 2. 小数点后保留两位,向上转型
String string = bigDecimal.setScale(2, RoundingMode.HALF_UP).toString();
// 3. 替换之前的值
gen.writeNumber(string);
}
}
————————————————————————————————————————————————
SpringMVC中使用FastJSON
1.添加依赖
2.安装FastJSON转换器
3.然后就可以使用FastJSON的注解
<!--添加Fastjson依赖-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.54</version>
</dependency>
</dependencies>
<!-- 开启注解驱动-->
<mvc:annotation-driven>
<!-- 安装FastJson,转换器 -->
<!--先在pom中导入fastjson依赖,然后在这里告诉springmvc要使用fastjson转换器-->
<mvc:message-converters>
<bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
<!-- 声明转换类型:json -->
<property name="supportedMediaTypes">
<list>
<value>application/json</value>
</list>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>