知識庫 / Spring / Spring MVC RSS 訂閱

Spring MVC 中的 JSON 參數

JSON,Spring MVC
HongKong
10
09:52 PM · Dec 05 ,2025

1. 概述

在本簡短教程中,我們將深入瞭解如何在 Spring MVC 中處理 JSON 參數。

首先,我們將對 JSON 參數進行一些背景介紹。然後,我們將深入探索如何通過 POST 和 GET 請求發送 JSON 參數。

2. JSON 參數在 Spring MVC 中

使用 JSON 發送或接收數據在 Web 開發中是一種常見的做法。 JSON 字符串的層次結構提供了一種更緊湊、更易於人類閲讀的方式來表示 HTTP 請求參數。

默認情況下,Spring MVC 提供內置的數據綁定功能,用於簡單的數據類型,例如 String為此,它在幕後使用一系列內置的 PropertyEditor

然而,在實際項目中,我們可能需要綁定更復雜的數據類型。 例如,將 JSON 參數映射到模型對象可能會非常方便。

3. 通過 POST 發送 JSON 數據

Spring 提供了一種簡單的方法來通過 POST 請求發送 JSON 數據。內置的 @RequestBody 標註可以自動將請求體中封裝的 JSON 數據反序列化為特定的模型對象。

通常情況下,我們無需自己解析請求體。 我們可以使用 Jackson 庫來完成所有繁重的工作

現在,讓我們看看如何在 Spring MVC 中通過 POST 請求發送 JSON 數據。

首先,我們需要創建一個模型對象來表示傳遞的 JSON 數據。例如,考慮 Product 類:

public class Product {

    private int id;
    private String name;
    private double price;

    // default constructor + getters + setters

}

其次,我們定義一個接受 POST 請求的 Spring 處理方法:

@PostMapping("/create")
@ResponseBody
public Product createProduct(@RequestBody Product product) {
    // custom logic
    return product;
}

如我們所見,產品 論點進行標註,並使用 @RequestBody 即可將客户端發送的 JSON 數據綁定

現在,我們可以使用 cURL 測試我們的 POST 請求:

curl -i \
-H "Accept: application/json" \
-H "Content-Type: application/json" \
-X POST --data \
  '{"id": 1,"name": "Asus Zenbook","price": 800}' "http://localhost:8080/spring-mvc-basics-4/products/create"

4. 通過 GET 發送 JSON 參數

Spring MVC 提供 @RequestParam 用於從 GET 請求中提取查詢參數。但是,與 @RequestBody 不同,@RequestParam 註解僅支持基本數據類型,如 intString

因此,要發送 JSON,我們需要將 JSON 參數定義為簡單的字符串。

這裏的問題是:我們如何將 JSON 參數(它是 String)轉換為 Product 類的對象?

答案很簡單!Jackson 庫提供的 ObjectMapper 類提供了一種靈活的方式來將 JSON 字符串轉換為 Java 對象

現在,讓我們看看如何通過 GET 請求在 Spring MVC 中發送 JSON 參數。首先,我們需要在控制器的另一個處理方法中創建 GET 請求的處理方法:

@GetMapping("/get")
@ResponseBody
public Product getProduct(@RequestParam String product) throws JsonMappingException, JsonProcessingException {
    Product prod = objectMapper.readValue(product, Product.class);
    return prod;
}

如上所示,readValue() 方法允許直接將 JSON 參數 product 序列化為一個 Product 類實例。

請注意,我們定義 JSON 查詢參數為 String 對象。如果我們要像使用 @RequestBody 時那樣,傳遞一個 Product 對象,會怎樣?

為了回答這個問題,Spring 通過自定義屬性編輯器提供了一個簡潔而靈活的解決方案。

首先,我們需要創建一個自定義屬性編輯器來封裝將 JSON 參數(作為 String 傳遞)轉換為 Product 對象 的邏輯:

public class ProductEditor extends PropertyEditorSupport {

    private ObjectMapper objectMapper;

    public ProductEditor(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

    @Override
    public void setAsText(String text) throws IllegalArgumentException {
        if (StringUtils.isEmpty(text)) {
            setValue(null);
        } else {
            Product prod = new Product();
            try {
                prod = objectMapper.readValue(text, Product.class);
            } catch (JsonProcessingException e) {
                throw new IllegalArgumentException(e);
            }
            setValue(prod);
        }
    }

}

接下來,讓我們將 JSON 參數綁定到 Product 類的一個對象上:

@GetMapping("/get2")
@ResponseBody
public Product get2Product(@RequestParam Product product) {
    // custom logic
    return product;
}

最後,我們需要添加拼圖的最後一塊。讓我們在我們的 Spring 控制器中註冊 ProductEditor

@InitBinder
public void initBinder(WebDataBinder binder) {
    binder.registerCustomEditor(Product.class, new ProductEditor(objectMapper));
}

請務必記住,我們需要對JSON參數進行URL編碼,以確保安全傳輸

因此,而不是:

GET /spring-mvc-basics-4/products/get2?product={"id": 1,"name": "Asus Zenbook","price": 800}

我們需要發送:

GET /spring-mvc-basics-4/products/get2?product=%7B%22id%22%3A%201%2C%22name%22%3A%20%22Asus%20Zenbook%22%2C%22price%22%3A%20800%7D

5. 結論

總而言之,我們學習瞭如何在 Spring MVC 中處理 JSON 數據。 在此過程中,我們展示瞭如何將 JSON 參數發送到 POST 和 GET 請求中。

發佈 評論

Some HTML is okay.