adam bien's blog

JSONB: How to Serialize Java Objects into Formatted JSON 📎

To serialize a POJO:

public class Post {
    public String title;
    public String content;

}

into a formatted JSON, you will have to add the following dependency to your pom.xml:

<dependency>
    <groupId>org.eclipse</groupId>
    <artifactId>yasson</artifactId>
    <version>1.0.7</version>
    <scope>test</scope>
</dependency>

The JsonbBuilder needs to be configured to output formatted JSON:


@Test
public void serializePost() {
    Post post = new Post();
    post.content = "hello, world";
    post.title = "a nice title";

    JsonbConfig config = new JsonbConfig().
        withFormatting(true);
    Jsonb jsonb = JsonbBuilder.newBuilder().
        withConfig(config).
        build();

    String serialized = jsonb.toJson(post);
    System.out.println(serialized);
}

The test above creates the following output:


{
    "content": "hello, world",
    "title": "a nice title"
}