原文地址:https://www.jianshu.com/p/63c5985fb48e
Jackson作為springMVC默認的MessageConverter(消息序列化工具),經常在項目中使用,如果熟悉Jackson常用的使用方法,特性化機制,就會事半功倍,極大提高前后端數據交互的靈活性。
maven依賴
<dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.9.5</version> </dependency>
使用jackson需要三個jar包,jackson-databind、jackson-core和jackson-annotations,添加一個依賴jackson-databind就可以擁有這三個jar包。
jackson基礎功能
jackson使用的最多的就是jackson-databind包,官方文檔地址是https://github.com/FasterXML/jackson-databind,使用jackson序列化對象使用ObjectMapper類,如下:
ObjectMapper objectMapper = new ObjectMapper();
User user = new User("zhangsan", "123456");
// class to json
String userStr = objectMapper.writeValueAsString(user);
// json to class
User user2 = objectMapper.readValue(userStr, User.class);
jackson常用注解使用
jackson注解主要涉及到的jar包為jackson-annotations.jar,官方文檔地址https://github.com/FasterXML/jackson-annotations/wiki/Jackson-Annotations
1. @JsonProperty 用在屬性或者方法上面,用於改變序列化時字段的名稱
public class User { @JsonProperty("user_name") public String username; public String password; } // 序列化為如下格式username變成了user_name {"password":"123456","user_name":"zhangsan"}
2. @JsonIgnoreProperties 用在類上面,用於在序列化時忽略指定字段
####@JsonIgnoreProperties({"username", "price"})
public class Pet {
private String username;
private String password;
private Date birthday;
private Double price;
}
// 指定序列化時忽略username、price字段
{"password":"123456","birthday":1533887811261}
3. @JsonIgnore 用在屬性上面,用於序列化時忽略該屬性
public class Pet {
@JsonIgnore
private String username;
private String password;
private Date birthday;
private Double price;
}
// @JsonIgnore加在屬性上面,使序列化時忽略該字段
{"password":"123456","birthday":1533888026016,"price":0.6}
4. @JsonFormat 用在Date時間類型屬性上面,用於序列化時間為需要的格式
public class Pet {
private String username;
private String password;
@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss", timezone="GMT+8")
private Date birthday;
private Double price;
}
// @JsonFormat加在屬性上面,用於jackson對時間格式規定,注意要指定中國時區為+8
{"username":"哈哈","password":"123456","birthday":"2018-08-10 16:17:51","price":0.6}
5. @JsonInclude 用在類上面,用於聲明在序列化時忽略一些沒有意義的字段,例如:屬性為NULL的字段
@JsonInclude(Include.NON_NULL)
public class Pet {
private String username;
private String password;
private Date birthday;
private Double price;
}
// @JsonInclude加在類上面,jackson序列化時會忽略無意義的字段,例如username和price是空值,那么就不序列化這兩個字段
{"password":"123456","birthday":1533890045175}
6. @JsonSerialize 用在類或屬性上面,用於指定序列化時使用的JsonSerialize類
一般會使用自定義的序列化器,例如自定義MyJsonSerializer,用來處理Double類型序列化時保留兩位小數,就非常好用
public class MyJsonSerializer extends JsonSerializer<Double>{ @Override public void serialize(Double value, JsonGenerator gen, SerializerProvider serializers) throws IOException, JsonProcessingException { if (value != null) gen.writeString(BigDecimal.valueOf(value). setScale(2, BigDecimal.ROUND_HALF_UP).toString()); // ROUND_HALF_UP四舍五入 } }
使用方式
public class Pet {
private String username;
private String password;
private Date birthday;
@JsonSerialize(using=MyJsonSerializer.class)
private Double price;
}
// 指定序列化price屬性時使用自定義MyJsonSerializer,對Double類型進行自定義處理,保留兩位小數
{"username":"哈哈","password":"123456","birthday":1533892290795,"price":"0.60"}
Jackson和SpringMVC整合使用
jackson作為springMVC官方推薦使用MessageConverter工具,並成為springMVC默認的MessageConverter工具,因此在springMVC中使用jackson非常簡單,springMVC會在需要json格式的response響應時,掃描項目中是否擁有jackson的相關類庫,如果擁有,那么默認就會使用jackson進行消息轉換,如果沒有,就會報異常。無需手動配置jackson。
當然也是可以手動配置的,在spring-application.xml中加入下面配置:
<mvc:annotation-driven> <mvc:message-converters register-defaults="true"> <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"></bean> </mvc:message-converters> </mvc:annotation-driven>
<mvc:annotation-driven> <mvc:message-converters register-defaults="true"> <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"> <constructor-arg name="objectMapper"> <bean class="com.fasterxml.jackson.databind.ObjectMapper"> <property name="dateFormat"> <bean class="java.text.SimpleDateFormat"> <constructor-arg index="0" value="yyyy-MM-dd HH:mm:ss" /> <constructor-arg index="1" value="#{T(java.util.Locale).SIMPLIFIED_CHINESE}" /> <property name="timeZone" value="GMT+8" /> </bean> </property> </bean> </constructor-arg> </bean> </mvc:message-converters> </mvc:annotation-driven>
個性化定制對於項目中使用jackson非常重要,實際使用中可以根據需求進行擴展,對MappingJackson2HttpMessageConverter進行設置。
jackson和spring-boot整合使用
同樣,jackson也是作為spring-boot的默認MessageConverter工具,他被包含在spring-boot-starter-web依賴中,這里主要說明spring-boot如何對jackson進行個性化配置,重寫WebMvcConfigurerAdapter類的configureMessageConverters方法即可,如下
@Configuration public class WebConfig extends WebMvcConfigurerAdapter { @Override public void configureMessageConverters(List<HttpMessageConverter<?>> converters) { ObjectMapper objectMapper = new ObjectMapper(); // 設置Date類型字段序列化方式 objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.SIMPLIFIED_CHINESE)); // 指定BigDecimal類型字段使用自定義的CustomDoubleSerialize序列化器 SimpleModule simpleModule = new SimpleModule(); simpleModule.addSerializer(BigDecimal.class, new CustomDoubleSerialize()); objectMapper.registerModule(simpleModule); MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter(objectMapper); converters.add(converter); } }
可以看出,spring-boot對於jackson的使用更加靈活。