1.使用默認的json轉換HttpessageConverter
Json是目前主流的前后端數據傳輸方式,SpringMVC中使用消息轉化器HttpMessageConverter對JSON的轉換提供了很好的支持,在SpringBoot中對相關配置做了進一步簡化。
pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
這個依賴中默認加入了jacjson-databind作為JSON處理器,此時不需要添加額外的Json處理器就可以返回json了。
public class Book { private String name; private String author; @JsonIgnore //過濾掉這個屬性 protected Float price; @JsonFormat(pattern = "yyyy-MM-dd") //格式化輸出這個屬性 private Date publicationDate; //省略getter/setter }
@RestController public class BookController { @GetMapping("/book") public Book book() { Book book = new Book(); book.setAuthor("羅貫中"); book.setName("三國演義"); book.setPrice(30f); book.setPublicationDate(new Date()); return book; } }
結果:
這是Springboot自帶的處理方式,如果采用這種方式,對於字段忽略,日期格式化等都可以使用注解實現。
Spring中默認提供的MappingJackson2HttpMessageConverter去實現json轉換的。
2.自定義轉換器
常見的JSON處理器除了Jackson-databind,還有Gson和fastjson
2.1使用Gson
Gson是Google的一個開源的JSON解析框架,使用他之前首先去除默認的jackson-databind,然后加入Gson依賴。
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <exclusions> <exclusion> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> </dependency>
SpringBoot中默認提供了Gson的自動轉換類GsonHttpMessageConverterConfiguration,因此可以像使用jackson-databind那樣直接使用Gson,但是在Gson進行轉換時,如果想對日期數據進行格式化,還需要自定義HttpMessageConverter。
protected static class GsonHttpMessageConverterConfiguration { @Bean @ConditionalOnMissingBean public GsonHttpMessageConverter gsonHttpMessageConverter(Gson gson) { GsonHttpMessageConverter converter = new GsonHttpMessageConverter(); converter.setGson(gson); return converter; } }
@ConditionalOnMissingBean注解表示當項目中沒有提供GsonHttpMessageConverter 時才會使用默認的GsonHttpMessageConverter,所以我們自己寫一個 GsonHttpMessageConverter就可以避免沒有GsonHttpMessageConverter從而使用默認的了。
@Configuration public class GsonConfig { @Bean GsonHttpMessageConverter gsonHttpMessageConverter() { GsonHttpMessageConverter converter = new GsonHttpMessageConverter(); GsonBuilder builder = new GsonBuilder(); //設置Gson解析時日期的格式 builder.setDateFormat("yyyy-MM-dd"); //設置Gson解析時修飾符為protected的字段時過濾掉它 builder.excludeFieldsWithModifiers(Modifier.PROTECTED); //創建Gson對象放入GsonHttpMessageConverter的實例並且返回converter Gson gson = builder.create(); converter.setGson(gson); return converter; } }
public class Book {
private String name;
private String author;
protected Float price; //字段被過濾掉
private Date publicationDate;
}
2.2使用fastjson
阿里巴巴的json解析框架,可以集成到SpringBoot中,不同於Gson,fastjson繼承后並不能立即使用,還需要開發者提供HttpMessageConverter后才可以使用。
同樣,去除jsckson-databind依賴,加入fastjson依賴
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <exclusions> <exclusion> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.47</version> </dependency>
配置fasjson的HttpMessageConverter
@Configuration public class MyFastJsonConfig { @Bean FastJsonHttpMessageConverter fastJsonHttpMessageConverter() { FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter(); FastJsonConfig config = new FastJsonConfig(); //設置json解析中一些細節,日期格式,數據編碼 config.setDateFormat("yyyy-MM-dd"); config.setCharset(Charset.forName("UTF-8")); //是否在生成的Json中輸出類名 //是否輸出value為null的數據 //生成的json格式化 //空集合輸出[]而非null //空字符串輸出“”而非null等配置 config.setSerializerFeatures( SerializerFeature.WriteClassName, SerializerFeature.WriteMapNullValue, SerializerFeature.PrettyFormat, SerializerFeature.WriteNullListAsEmpty, SerializerFeature.WriteNullStringAsEmpty ); converter.setFastJsonConfig(config); return converter; } }
若輸出中文有亂碼:spring.http.encoding.force-response=true
對於FastJsonHttpMessageConverter 的配置,還有一種方式
引入spring-boot-starter-web后,他依賴spring-boot-autoconfigure,在這個自動化配置中,有一個WebMvcAutoConfiguration類提供了對SpringMVC最基本的配置如果希望自己配置只需要實現WebMvcConfigurer接口即可。
@Configuration public class MyWebMvcConfig implements WebMvcConfigurer {
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) { FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter(); FastJsonConfig config = new FastJsonConfig(); config.setDateFormat("yyyy-MM-dd"); config.setCharset(Charset.forName("UTF-8")); config.setSerializerFeatures( SerializerFeature.WriteClassName, SerializerFeature.WriteMapNullValue, SerializerFeature.PrettyFormat, SerializerFeature.WriteNullListAsEmpty, SerializerFeature.WriteNullStringAsEmpty ); converter.setFastJsonConfig(config); converters.add(converter); }
}
Jackson相關注解:
使用Jackson相關的注解時一定要注意自己定義的屬性命名是否規范。
命名不規范時會失去效果。(例如Ename ,Eage 為不規范命名。“nameE”,“ageE”為規范命名,如果使用@JsonIgnore注解不起效時請注意一下你的屬性名字是否規范
1、@JsonIgnoreProperties
此注解是類注解,作用是json序列化時將java bean中的一些屬性忽略掉,序列化和反序列化都受影響。
寫法將此標簽加在model 類的類名上 ,可以多個屬性也可以單個屬性
//生成json時將name和age屬性過濾 @JsonIgnoreProperties({"name"},{"age"}) public class user { private String name; private int age; }
2、@JsonIgnore
此注解用於屬性或者方法上(最好是屬性上),作用和上面的@JsonIgnoreProperties一樣。
生成json 時不生成age 屬性
public class user { private String name; @JsonIgnore private int age; }
3、@JsonFormat
此注解用於屬性或者方法上(最好是屬性上),可以方便的把Date類型直接轉化為我們想要的模式,比如@JsonFormat(pattern = “yyyy-MM-dd HH-mm-ss”)
4、@JsonSerialize
此注解用於屬性或者getter方法上,用於在序列化時嵌入我們自定義的代碼,比如序列化一個double時在其后面限制兩位小數點。
5、@JsonDeserialize
此注解用於屬性或者setter方法上,用於在反序列化時可以嵌入我們自定義的代碼,類似於上面的@JsonSerialize
6、@Transient
如果一個屬性並非數據庫表的字段映射,就務必將其標示為@Transient,否則ORM框架默認其注解為@Basic;
//表示該字段在數據庫表中沒有
@Transient public int getAge() { return 1+1; }