Java如何使用Jackson轻松打印JSON字符串?

下面的示例演示如何漂亮地打印Jackson库生成的JSON字符串。为了产生格式正确的JSON字符串,我们创建ObjectMapper实例并启用该SerializationFeature.INDENT_OUTPUT功能。要启用此功能,我们需要调用的enable()方法ObjectMapper并提供要启用的功能。

ObjectMapper mapper = new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT);
String json = mapper.writeValueAsString(recording);
System.out.println(json);

在下面的第二个示例中,我们格式化未格式化的JSON字符串。为此,我们使用ObjectMapper的readValue(String, Class<T>)方法,该方法接受JSON字符串Object.class作为值类型。该readValue()方法返回Object。要格式化JSON对象,我们调用mapper.writerWithDefaultPrettyPrinter().writeValueAsString(Object)。这将产生一个漂亮的JSON格式。

ObjectMapper mapper = new ObjectMapper();
Object jsonObject = mapper.readValue(json, Object.class);
String prettyJson = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(jsonObject);
System.out.println(prettyJson);

以下是完整的代码段。

package org.nhooo.example.jackson;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;

import java.io.IOException;
import java.time.LocalDate;
import java.time.Month;

public class JsonIndentOutput {
    public static void main(String[] args) {
        JsonIndentOutput.formatObjectToJsonString();
        JsonIndentOutput.formatJsonString();
    }

    private static void formatObjectToJsonString() {
        Recording recording = new Recording();
        recording.setId(1L);
        recording.setTitle("Yellow Submarine");
        recording.setReleaseDate(LocalDate.of(1969, Month.JANUARY, 17));
        recording.setArtist(new Artist(1L, "The Beatles"));
        recording.setLabel(new Label(1L, "Apple"));

        ObjectMapper mapper = new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT);
        try {
            String json = mapper.writeValueAsString(recording);
            System.out.println(json);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
    }

    private static void formatJsonString() {
        String json = "{\"id\":1,\"title\":\"Yellow Submarine\",\"releaseDate\":\"1969-01-17\",\"artist\":{\"id\":1,\"name\":\"The Beatles\"},\"label\":{\"id\":1,\"name\":\"Apple\"}}";
        ObjectMapper mapper = new ObjectMapper();
        try {
            Object jsonObject = mapper.readValue(json, Object.class);
            String prettyJson = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(jsonObject);
            System.out.println(prettyJson);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

上面的代码片段将漂亮地打印以下JSON字符串:

{
  "id" : 1,
  "title" : "Yellow Submarine",
  "releaseDate" : "1969-01-17",
  "artist" : {
    "id" : 1,
    "name" : "The Beatles"
  },
  "label" : {
    "id" : 1,
    "name" : "Apple"
  }
}

这是Recording类的结构。

package org.nhooo.example.jackson;

import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;

import java.time.LocalDate;
import java.util.Objects;

public class Recording {
    private Long id;
    private String title;

    @JsonDeserialize(using = LocalDateDeserializer.class)
    @JsonSerialize(using = LocalDateSerializer.class)
    private LocalDate releaseDate;

    private Artist artist;
    private Label label;

    public Recording() {
    }

    public Recording(Long id, String title, LocalDate releaseDate) {
        this.id = id;
        this.title = title;
        this.releaseDate = releaseDate;
    }

    // 吸气剂和二传手
}

Maven依赖

<!-- http://repo1.maven.org/maven2/com/fasterxml/jackson/core/jackson-databind/2.8.6/jackson-databind-2.8.6.jar -->
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.8.6</version>
</dependency>