SpringBoot解析JSON數(shù)據(jù)的三種方案
1 JSON簡介
JSON(JavaScript Object Notation) 是一種輕量級的數(shù)據(jù)交換格式。易于人閱讀和編寫。同時也易于機器解析和生成。JSON是一個標(biāo)記符的序列。這套標(biāo)記符包含六個構(gòu)造字符、字符串、數(shù)字和三個字面名。JSON是一個序列化的對象或數(shù)組。
2 Spring Boot默認(rèn)的JSON解析
Spring Boot項目中當(dāng)我們添加了spring-boot-starter-web依賴,就默認(rèn)提供了Jackson用于解析Json
2.1 使用示例
創(chuàng)建一個實體類
@Component public class User { private long id; private String username; private Date birthday; public long getId() { return id; } public void setId(long id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } }
創(chuàng)建一個Controller類,用于頁面訪問:
@RestController public class ShowController { @GetMapping("/show") public List<User> show(){ List<User> users=new ArrayList<User>(); for (int i = 0; i < 5; i++) { User user=new User(); user.setId(i); user.setUsername("張三"+i); user.setBirthday(new Date()); users.add(user); } return users; } }
啟動項目,瀏覽器訪問,可以看到默認(rèn)返回了JSON格式的數(shù)據(jù)
可以看到上面的Date類型數(shù)據(jù)需要我們自定義格式,在實體類中date屬性上添加JsonFormat注解可以實現(xiàn):
@JsonFormat(pattern = "YYYY-MM-dd") private Date birthday;
修改后重啟項目,瀏覽器訪問:
但是當(dāng)很多類都需要配置自定義格式時,就需要添加多個注解,這樣是麻煩且不利于后期維護(hù)的。所以我們需要修改全局JSON格式。
下面以修改Date類型數(shù)據(jù)為例:
2.2 修改特定數(shù)據(jù)的全局JSON格式
JSON的解析離不開HttpMessageConvert,HttpMessageConvert是一個消息轉(zhuǎn)換工具,主要有兩方面的功能:
- 將服務(wù)端返回的對象序列化成JSON字符串
- 將前端傳來的JSON字符串反序列化成Java對象
SpringMVC中默認(rèn)配置了Jackson和GsonHttpMessageConverter,Spring Boot中對此做了自動化配置,主要由以下兩個類實現(xiàn):
org.springframework.boot.autoconfigure.http.JacksonHttpMessageConvertersConfiguration org.springframework.boot.autoconfigure.http.GsonHttpMessageConvertersConfiguration
JacksonHttpMessageConvertersConfiguration的源碼如下:
@Configuration( proxyBeanMethods = false ) class JacksonHttpMessageConvertersConfiguration { JacksonHttpMessageConvertersConfiguration() { } @Configuration( proxyBeanMethods = false ) @ConditionalOnClass({XmlMapper.class}) @ConditionalOnBean({Jackson2ObjectMapperBuilder.class}) protected static class MappingJackson2XmlHttpMessageConverterConfiguration { protected MappingJackson2XmlHttpMessageConverterConfiguration() { } @Bean @ConditionalOnMissingBean public MappingJackson2XmlHttpMessageConverter mappingJackson2XmlHttpMessageConverter(Jackson2ObjectMapperBuilder builder) { return new MappingJackson2XmlHttpMessageConverter(builder.createXmlMapper(true).build()); } } //配置類注解 @Configuration( proxyBeanMethods = false ) /* *下面幾個是條件注解,當(dāng)添加了Jackson依賴,就有了ObjectMapper.class和屬性,后面的配置就會生效 */ @ConditionalOnClass({ObjectMapper.class}) @ConditionalOnBean({ObjectMapper.class}) @ConditionalOnProperty( name = {"spring.http.converters.preferred-json-mapper"}, havingValue = "jackson", matchIfMissing = true ) static class MappingJackson2HttpMessageConverterConfiguration { MappingJackson2HttpMessageConverterConfiguration() { } /* *@ConditionalOnMissingBean的意思就是如果我們沒有配置這個Bean,就自動創(chuàng)建一個默認(rèn)的,當(dāng)我們配置了就使用我們配置的Bean,不再創(chuàng)建 */ @Bean @ConditionalOnMissingBean( value = {MappingJackson2HttpMessageConverter.class}, ignoredType = {"org.springframework.hateoas.server.mvc.TypeConstrainedMappingJackson2HttpMessageConverter", "org.springframework.data.rest.webmvc.alps.AlpsJsonHttpMessageConverter"} ) /* *MappingJackson2HttpMessageConverter就是Jackson的消息轉(zhuǎn)換工具類 */ MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter(ObjectMapper objectMapper) { /* *JSON中序列化對象主要用ObjectMapper工具類 */ return new MappingJackson2HttpMessageConverter(objectMapper); } } }
通過查看上面源碼,可以知道我們修改生成的JSON的全局格式有以下兩種方式:
2.2.1 自定義MappingJackson2HttpMessageConverter
自己創(chuàng)建一個MappingJackson2HttpMessageConverter,取代JacksonHttpMessageConvertersConfiguration中項目自帶的。
例:
在上面創(chuàng)建的項目中,首先刪除JsonFormat注解,下面新建一個配置類,內(nèi)容如下:
@Configuration public class WebMVCConfig { @Bean MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter(){ MappingJackson2HttpMessageConverter converter=new MappingJackson2HttpMessageConverter(); ObjectMapper om=new ObjectMapper(); om.setDateFormat(new SimpleDateFormat("YYYY/MM/dd")); converter.setObjectMapper(om); return converter; } }
2.2.2 自定義ObjectMapper
通過上面的類可以看到類中主要起作用的是ObjectMapping,上面的JacksonHttpMessageConvertersConfiguration可以看ObjectMapping是直接注入的。它是在配置類JacksonAutoConfiguration 中提供的。
修改WebMVCConfig類,內(nèi)容如下:
@Configuration public class WebMVCConfig { @Bean ObjectMapper objectMapper(){ ObjectMapper om=new ObjectMapper(); om.setDateFormat(new SimpleDateFormat("YYYY/MM/DD")); return om; } }
兩種方式都是可以的,瀏覽器訪問:
3 使用Gson處理JSON
3.1 使用示例
基于上面創(chuàng)建的項目進(jìn)行修改,首先去掉spring-boot-starter-json依賴。然后添加gson依賴:
然后將配置類的jackson部分和一些導(dǎo)入的jackson包注釋或刪除,然后啟動項目。
可以看到日期格式是Gson默認(rèn)的。需要進(jìn)行修改
3.2 修改特定數(shù)據(jù)的全局JSON格式
GsonHttpMessageConvertersConfiguration的部分源碼如下:
@Configuration( proxyBeanMethods = false ) @ConditionalOnBean({Gson.class}) @Conditional({GsonHttpMessageConvertersConfiguration.PreferGsonOrJacksonAndJsonbUnavailableCondition.class}) static class GsonHttpMessageConverterConfiguration { GsonHttpMessageConverterConfiguration() { } @Bean @ConditionalOnMissingBean GsonHttpMessageConverter gsonHttpMessageConverter(Gson gson) { GsonHttpMessageConverter converter = new GsonHttpMessageConverter(); converter.setGson(gson); return converter; }
可以看到與Jackson差不多,所以可以仿照J(rèn)ackson進(jìn)行修改
3.2.1 自定義GsonHttpMessageConverter
@Configuration public class WebMVCConfig { @Bean GsonHttpMessageConverter gsonHttpMessageConverter(){ GsonHttpMessageConverter converter=new GsonHttpMessageConverter(); converter.setGson(new GsonBuilder().setDateFormat("YYYY-MM-DD").create()); return converter; } }
3.2.2 自定義Gson對象
上面配置主要用的是Gson對象,Gson對象是在GsonAutoConfiguration類中,當(dāng)我們沒有配置時為我們創(chuàng)建的。然后在GsonHttpMessageConverter中使用。我們也可以自己創(chuàng)建一個Gson對象:
@Configuration public class WebMVCConfig { @Bean Gson gson(){ return new GsonBuilder().setDateFormat("YYYY-MM-DD").create(); } }
兩種方式都是可以的,瀏覽器訪問:
4 使用FastJson處理JSON
4.1 使用示例
以上面創(chuàng)建的項目為基礎(chǔ),去除Jackson依賴,添加FastJson依賴:
因為Spring Boot沒有提供相關(guān)的自動化配置類,所以我們需要手動創(chuàng)建FastJson的消息轉(zhuǎn)換工具類:
@Configuration public class WebMVCConfig { @Bean FastJsonHttpMessageConverter fastJsonHttpMessageConverter(){ FastJsonHttpMessageConverter converter=new FastJsonHttpMessageConverter(); return converter; } }
啟動項目,瀏覽器訪問:
可以看到日期格式變成了FastJson的格式了。需要進(jìn)行修改。
4.2 修改特定數(shù)據(jù)的全局JSON格式
FastJson是直接在 FastJsonHttpMessageConverter類中進(jìn)行修改,新建一個FastJsonConfig對象,此時需要對編碼進(jìn)行設(shè)置,否則會出現(xiàn)亂碼:
@Configuration public class WebMVCConfig { @Bean FastJsonHttpMessageConverter fastJsonHttpMessageConverter(){ FastJsonHttpMessageConverter converter=new FastJsonHttpMessageConverter(); FastJsonConfig config=new FastJsonConfig(); // 處理中文亂碼問題 List<MediaType> fastMediaTypes = new ArrayList<>(); fastMediaTypes.add(MediaType.APPLICATION_JSON_UTF8); converter.setSupportedMediaTypes(fastMediaTypes); //設(shè)置日期格式 config.setDateFormat("YYYY-MM-DD"); converter.setFastJsonConfig(config); return converter; } }
以上就是SpringBoot解析JSON數(shù)據(jù)的三種方案的詳細(xì)內(nèi)容,更多關(guān)于SpringBoot解析JSON數(shù)據(jù)的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Springboot整合多數(shù)據(jù)源配置流程詳細(xì)講解
這篇文章主要介紹了Springboot整合多數(shù)據(jù)源配置流程,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧2023-03-03JAVA中時間戳與LocalDateTime互相轉(zhuǎn)換代碼例子
最近在編碼過程中遇到將時間戳轉(zhuǎn)化為 LocalDateTime,所以這里給總結(jié)下,這篇文章主要給大家介紹了關(guān)于JAVA中時間戳與LocalDateTime互相轉(zhuǎn)換的相關(guān)資料,需要的朋友可以參考下2023-11-11淺談Java并發(fā) J.U.C之AQS:CLH同步隊列
AQS內(nèi)部維護(hù)著一個FIFO隊列,該隊列就是CLH同步隊列。下面小編來簡單介紹下這個隊列2019-05-05java synchronized實現(xiàn)可見性過程解析
這篇文章主要介紹了java synchronized實現(xiàn)可見性過程解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2019-09-09