在Java中格式化JSON

Jackson
Remote
0
07:43 PM · Nov 30 ,2025

1. 簡介

在本教程中,我們將深入研究如何使用 Java 格式化 JSON 數據,以提高其可讀性。

通常,在處理大型 JSON 對象時,理解和調試它們可能是一項艱鉅的任務。因此,採用格式化 JSON 對象的做法變得至關重要。

為了實現這一點,我們將利用 Jackson 和 Gson 庫的功能,這些庫提供方便的方法來生成格式良好的 JSON 輸出。

2. Pretty Print JSON using Jackson

為了使用 Jackson 對 JSON 進行美化打印,首先需要在 pom.xml 文件中添加以下依賴項:

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.17.2</version>
</dependency>

始終從 Maven 中央倉庫使用最新版本 jackson-databind

2.1. On-Demand 美化打印

為了實現 JSON 的按需美化打印,可以使用 writeWithDefaultPrettyPrinter() 方法:

String uglyJsonString = "{\"one\":\"AAA\",\"two\":[\"BBB\",\"CCC\"],\"three\":{\"four\":\"DDD\",\"five\":[\"EEE\",\"FFF\"]}}"; 

public String prettyPrintJsonUsingDefaultPrettyPrinter(String uglyJsonString) {
    ObjectMapper objectMapper = new ObjectMapper();
    Object jsonObject = objectMapper.readValue(uglyString, Object.class);
    String prettyJson = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(jsonObject);
    return prettyJson;
}

結果是格式良好的 JSON 對象:

@Test
public void shouldPrettyPrintJsonStringUsingDefaultPrettyPrinter() throws JsonProcessingException {
    JsonPrettyPrinter jsonPrettyPrinter = new JsonPrettyPrinter();
    String formattedJsonString = jsonPrettyPrinter.prettyPrintJsonUsingDefaultPrettyPrinter(uglyJsonString);
    System.out.println(formattedJsonString);
}
// output:
{
    "one" : "AAA",
    "two" : [ "BBB", "CCC" ],
    "three" : {
        "four" : "DDD",
        "five" : [ "EEE", "FFF" ]
    }
}

2.2. 全局美化打印

通過全局啓用 INDENT_OUTPUT 設置,我們可以生成格式良好的 JSON 字符串,並進行美化打印。這確保了系統中的 JSON 輸出始終以可讀的方式進行格式化。

現在,讓我們繼續全局啓用 INDENT_OUTPUT 設置:

public String prettyPrintUsingGlobalSetting(String uglyJsonString) {
    ObjectMapper mapper = new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT);
    Object jsonObject = mapper.readValue(uglyJsonString, Object.class);
    String prettyJson = mapper.writeValueAsString(jsonObject);
    return prettyJson;
}

結果是格式良好的 JSON 對象:

@Test
public void shouldPrettyPrintJsonStringUsingGlobalSetting() throws JsonProcessingException {
    JsonPrettyPrinter jsonPrettyPrinter = new JsonPrettyPrinter();
    String formattedJsonString = jsonPrettyPrinter.prettyPrintUsingGlobalSetting(uglyJsonString);
    System.out.println(formattedJsonString);
}
// output:
{
    "one" : "AAA",
    "two" : [ "BBB", "CCC" ],
    "three" : {
        "four" : "DDD",
        "five" : [ "EEE", "FFF" ]
    }
}

3. 使用 Gson 美化 JSON

首先添加 Gson Maven 依賴:

<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.10.1</version>
</dependency>

始終使用 Maven 中央倉庫的最新版本 gson

要美化 JSON,我們將使用 GsonBuilder 的 setPrettyPrinting() 方法

public String prettyPrintUsingGson(String uglyJson) {
    Gson gson = new GsonBuilder().setPrettyPrinting().create();
    JsonElement jsonElement = JsonParser.parseString(uglyJsonString);
    String prettyJsonString = gson.toJson(jsonElement);
    return prettyJsonString;
}

結果是格式良好的 JSON 對象:

@Test
public void shouldPrettyPrintJsonStringUsingGson() {
    JsonPrettyPrinter jsonPrettyPrinter = new JsonPrettyPrinter();
    String formattedJsonString = jsonPrettyPrinter.prettyPrintUsingGson(uglyJsonString);
    System.out.println(formattedJsonString);
}
// 輸出:
{
    "one": "AAA",
    "two": [
        "BBB",
        "CCC"
    ],
    "three": {
        "four": "DDD",
        "five": [
            "EEE",
            "FFF"
        ]
    }
}

4. 結論

在本文中,我們探討了多種用於在 Java 中實現 JSON 數據美化排版的各種方法。

user avatar
0 位用戶收藏了這個故事!
收藏

發佈 評論

Some HTML is okay.