返回JSON數據


默認實現

Json是目前主流的前后端數據傳輸方式,SptringMVC中使用消息轉換器HttpMessageConverter對JSON的轉換提供了很好的支持,在SpringBoot中更進一步,對相關的配置做了簡化。默認情況下,當開發者新創建一個SpringBoot項目后,添加web依賴,這個依賴默認加入了jackson-databind作為JSON處理器,此時不需要添加額外的JSON處理器就能返回一段JSON了。

HttpMessageConverter,看名字就知道,這是一個消息裝換工具,有兩個方面的功能:

  1. 將服務端返回的對象序列化成JSON字符串
  2. 將前端傳來的JSON字符串反序列化成Jason對象

所有的JSON對象都離不開相關的HttpMessageConverter

SpringMVC自動配置了Jackson和Gson的HttpMessageConverter,SpringBoot中又對此做了自動化配置

  1. org.springframework.boot.autoconfigure.http.JacksonHttpMessageConvertersConfiguration
  2. org.springframework.http.converter.json.GsonHttpMessageConverter

所以用戶使用Jackson和Gson的話,沒有其他額外配置,則只需要添加依賴即可

使用Jackson

bean

public class User {
    private Integer id;
    private String username;
    private String address;
    private Date birthday;
...
}

controller

@RestController
public class UserController {
    @GetMapping("users")
    public List<User> getAllUser(){
        List<User> users = new ArrayList<User>();

        for (int i = 0; i < 10; i++) {
            User user = new User();
            user.setId(i);
            user.setUsername("java技術"+i);
            user.setAddress("www.qwl.com"+i);
            user.setBirthday(new Date());
            users.add(user);
        }
        return users;
    }
}

運行結果

自定義轉換器

可以看出我們重寫MappingJackson2XmlHttpMessageConverter

@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;
    }
}

運行

從上面可以知道起關鍵作用的是ObjectMapper

@Bean
ObjectMapper objectMapper(){
    ObjectMapper om = new ObjectMapper();
    om.setDateFormat(new SimpleDateFormat("yyyy/MM/dd"));
    return om;
}

運行一樣起作用

使用Gson

排除jackson,添加Gson

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <exclusions>
        <exclusion>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-json</artifactId>
        </exclusion>
    </exclusions>
</dependency>

<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
</dependency>
@Configuration
public class WebMvcConfig {

    @Bean
    GsonHttpMessageConverter gsonHttpMessageConverter(){
        GsonHttpMessageConverter converter = new GsonHttpMessageConverter();
        converter.setGson(new GsonBuilder().setDateFormat("yyyy/MM/dd").create());
        return converter;

    }
}

或者

@Bean
Gson gson() {
    return new GsonBuilder().setDateFormat("yyyy/MM/dd").create();
}

使用fastjson

fastjson 是阿里巴巴的一個開源JSON 解析框架, 是目前JSON 解析速度最快的開源框架,該框架也可以集成到Spring Boot 中。不同於Gson, fastjson 繼承完成之后並不能立馬使用, 需要開
發者提供相應的HttpMessageConverter 后才能使用,集成fastjson 的步驟如下。
首先除去j ackson-databind 依賴,引入fastjson 依賴:

然后配置fastjson的HttpMessageConverter:

代碼解釋:

  • 自定義MyFastJsonConfig,完成對FastJsonHttpMessageConverter Bean的提供。
  • 第7~ 15 行分別配直了JSON 解析過程的一些細節,例如日期格式、數據編碼、是否在生成的JSON 中輸出類名、是否輸出value 為null 的數據、生成的JSON 格式化、空集合輸出口而非null 、空字符串輸出“”而非null 等基本配置。
    MyFastJsonConfig 配置完成后,還需要配置一下響應編碼,否則返回的JSON 中文會亂碼,在application.properties中添加如下配置:
spring.http.encoding.force-response=true

接下來提供BookController 進行測試。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM