首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 綜合教學

Spring MVC 返回 JSON 數據完整配置指南:Jackson 整合與實戰

     編輯:Java 綜合教學

Spring MVC 返回 JSON 數據完整配置指南:Jackson 整合與實戰

前後端分離架構下,Controller 直接返回 JSON 是標準做法。Spring MVC 內置 `HttpMessageConverter` 機制,配合 Jackson 庫可實現對象自動序列化為 JSON。本文詳述 Maven 依賴、XML 配置、前端調用、Controller 寫法全鏈路。

一、Maven 依賴

<dependencies>
    <!-- Jackson 核心 (Spring MVC 4.x 默認整合) -->
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.9.10</version>
    </dependency>
    <!-- 兼容舊版 codehaus 依賴 (可選) -->
    <dependency>
        <groupId>org.codehaus.jackson</groupId>
        <artifactId>jackson-core-asl</artifactId>
        <version>1.9.13</version>
    </dependency>
    <dependency>
        <groupId>org.codehaus.jackson</groupId>
        <artifactId>jackson-mapper-asl</artifactId>
        <version>1.9.13</version>
    </dependency>
</dependencies>

建議統一使用 `com.fasterxml.jackson` 系列 (Jackson 2.x),`codehaus` 為 1.x 老版本,僅為兼容歷史代碼保留。

二、Spring MVC 配置啟用 JSON 轉換器

<beans xmlns:mvc="https://www.springframework.org/schema/mvc" ...>
    <!-- 1. 啟用註解驅動,自動註冊 RequestMappingHandlerMapping/Adapter 及 默認 HttpMessageConverter -->
    <mvc:annotation-driven>
        <mvc:message-converters>
            <!-- 2. 顯式配置 MappingJackson2HttpMessageConverter (Jackson 2.x) -->
            <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
                <property name="supportedMediaTypes">
                    <list>
                        <value>application/json;charset=UTF-8</value>
                        <value>text/html;charset=UTF-8</value>
                    </list>
                </property>
                <!-- 可選:自定義 ObjectMapper -->
                <property name="objectMapper">
                    <bean class="com.fasterxml.jackson.databind.ObjectMapper">
                        <property name="dateFormat">
                            <bean class="java.text.SimpleDateFormat">
                                <constructor-arg value="yyyy-MM-dd HH:mm:ss"/>
                            </bean>
                        </property>
                        <property name="serializationInclusion">
                            <value type="com.fasterxml.jackson.annotation.JsonInclude.Include">NON_NULL</value>
                        </property>
                    </bean>
                </property>
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>
</beans>

若不顯式配置 ``,`<mvc:annotation-driven/>` 會自動註冊 `MappingJackson2HttpMessageConverter`(類路徑下有 Jackson 2.x 時),默認支持 `application/json`。

三、前端 AJAX 調用

<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
function loadUsers() {
    $.ajax({
        type: "POST",
        url: "/api/users",           // 對應 Controller @RequestMapping
        dataType: "json",            // 預期返回 JSON
        contentType: "application/json", // 發送 JSON 時需設置
        data: JSON.stringify({ page: 1, size: 10 }), // 發送複雜對象時
        success: function(resp) {
            // resp 為 JSON 對象/數組,直接操作
            var html = '<table><tr><th>ID</th><th>用戶名</th></tr>';
            $.each(resp, function(i, user) {
                html += '<tr><td>' + user.id + '</td><td>' + user.username + '</td></tr>';
            });
            html += '</table>';
            $('#userTable').html(html);
        },
        error: function(xhr) {
            alert('加載失敗: ' + xhr.status);
        }
    });
}
</script>

四、Controller 實現

方式 1:@ResponseBody + 返回對象 (推薦,最簡潔)

@RestController // 組合 @Controller + @ResponseBody
@RequestMapping("/api")
public class UserController {

    @Autowired private UserService userService;

    @GetMapping("/users")
    public List listUsers(@RequestParam(defaultValue = "1") int page,
                                @RequestParam(defaultValue = "10") int size) {
        return userService.findPage(page, size); // 直接返回 List,自動序列化為 JSON 數組
    }

    @GetMapping("/users/{id}")
    public User getUser(@PathVariable Long id) {
        return userService.findById(id); // 返回單對象,序列化為 JSON 對象
    }

    @PostMapping("/users")
    public Map createUser(@RequestBody User user) {
        User saved = userService.save(user);
        Map resp = new HashMap<>();
        resp.put("code", 200);
        resp.put("message", "創建成功");
        resp.put("data", saved);
        return resp; // Map 也可直接序列化
    }
}

方式 2:ModelAndView + MappingJackson2JsonView (舊版兼容)

@Controller
@RequestMapping("/legacy")
public class LegacyController {

    @RequestMapping(value = "/data", method = RequestMethod.GET)
    public ModelAndView getData() {
        Map map = new HashMap<>();
        map.put("user1", new User(1, "Alice"));
        map.put("user2", new User(2, "Bob"));
        // 指定視圖為 MappingJackson2JsonView,模型數據直接轉 JSON
        return new ModelAndView(new MappingJackson2JsonView(), map);
    }
}

五、常見問題與解決

問題原因解決
返回中文亂碼默認 ISO-8859-1 編碼配置 produces="application/json;charset=UTF-8" 或 MappingJackson2HttpMessageConverter supportedMediaTypes 包含 UTF-8
日期格式為時間戳Jackson 默認序列化 Date 為長整數ObjectMapper 設置 dateFormat 或 @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss")
循環引用報錯雙向關聯 (User→Order→User)@JsonIgnore / @JsonManagedReference + @JsonBackReference / 配置 ObjectMapper.setSerializationInclusion
Null 字段不輸出默認輸出 nullObjectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL)
406 Not Acceptable請求 Accept 頭不匹配前端設置 dataType: "json" 或 Accept: application/json

六、最佳實踐

  1. 全局統一使用 `@RestController`,簡化代碼。
  2. 定義統一響應封裝類 `Result` (code, message, data),配合全局異常處理器返回標準 JSON 格式。
  3. 日期類型統一使用 Java 8 `LocalDateTime` + `@JsonFormat`,避免 `java.util.Date` 時區問題。
  4. 敏感字段(密碼、身份證)加 `@JsonIgnore` 或脫敏序列化器。
  5. 大數據量列表分頁時,返回 `PageResult` 包含 total, list,避免一次性傳輸過大 JSON。

掌握 Spring MVC + Jackson JSON 整合,是構建現代 RESTful API 的核心基礎技能。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved