spring boot2 (30)-Jackson和ObjectMapper

在spring boot中,默認使用Jackson來實現java對象到json格式的序列化與反序列化。第3篇講的@RequestBody和@ResponseBody的轉換,最終都是由Jackson來完成的。

ObjectMapper基本用法

Jackson的轉換是通過ObjectMapper對象來實現的,spring boot內部自動配置了一個ObjectMapper對象,我們可以直接用。

	@Autowired
	ObjectMapper objectMapper;
	
	@GetMapping("/hello")
	public void hello() throws IOException {
		
		User user1 = new User();
		user1.setId("1");
		user1.setName("tom");
		//序列化
		String json = objectMapper.writeValueAsString(user1);
		System.out.println(json);
		
		//反序列化
		User user2 = objectMapper.readValue(json, User.class);
		System.out.println(user2.getId());
		System.out.println(user2.getName());

writeValueAsString:是將參數中的java對象序列化爲json字符串。

readValue:是將json字符串反序列化爲java對象,User.class就是指定對象的類型。

最終輸出如下


泛型的反序列化

上面的方法同樣適用於集合類型,但如果是包含泛型的集合則需要使用以下兩種方法之一
		String json = "[{\"id\":\"1\",\"name\":\"tom\"},{\"id\":\"2\",\"name\":\"jerry\"}]";
		JavaType javaType = objectMapper.getTypeFactory().constructParametricType(List.class, User.class);
		List<User> list = objectMapper.readValue(json, javaType);

或者

		String json = "[{\"id\":\"1\",\"name\":\"tom\"},{\"id\":\"2\",\"name\":\"jerry\"}]";
		List<User> list = objectMapper.readValue(json, new TypeReference<List<User>>() {});

properties常用參數配置

#日期類型格式
spring.jackson.date-format=yyyy-MM-dd HH:mm:ss
#日期類型使用中國時區
spring.jackson.time-zone=GMT+8
#序列化所有參數
spring.jackson.default-property-inclusion=always

spring.jackson.date-format:當序列化對象中包含日期類型的參數時,配置其轉換的格式,如yyyy-MM-dd HH:mm:ss

spring.jackson.time-zone:有些日期數據可能並不是中國時區,設置GMT+8可將其轉換爲中國時區

spring.jackson.default-property-inclusion:需要進行序列化的參數,默認值爲always指所有。還可配置如下值:

  • non_null:爲null的參數不序列化。
  • non_empty:爲空的參數不序列化,如""、null、沒有內容的new HashMap()等都算。Integer的0不算空。
  • non_default:爲默認值的參數不序列化,以上都算。另外,如Integer的0等也算默認值。

不序列化的參數:指java對象轉換爲json字符串時,其中不包含該參數。如當id=1,name=null時,always默認序列化爲


如配置了不序列化爲null的值,結果如下


常用註解

@JsonProperty:如下,假如id=1,轉換爲json時將輸出key=1
	@JsonProperty("key")
	Integer id;

@JsonIgnore:如下,不序列化id參數

	@JsonIgnore
	Integer id;

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章