adam bien's blog

Serializing a Collection of Java Records into a JSON Array 📎

A collection (Set) of Java Record instances:

public record Link(String text, String uri) {}

can be serialized with JSON-B into a JSON array:


import org.junit.jupiter.api.Test;
import java.util.Set;
import javax.json.bind.Jsonb;
import javax.json.bind.JsonbBuilder;

public class JSONBTest {

    @Test
    public void serialize() {
        var links = Set.of(new Link("json-b", "http://json-b.net"),
                            new Link("jakarta ee", "https://jakarta.ee"),
                            new Link("microprofile", "https://microprofile.io"));
        Jsonb jsonb = JsonbBuilder.create();
        var jsonArray = jsonb.toJson(links);
        System.out.println(jsonArray);
    }
}

The code above generates the following output:

[{"text":"jakarta ee","uri":"https://jakarta.ee"},{"text":"microprofile","uri":"https://microprofile.io"},{"text":"json-b","uri":"http://json-b.net"}]

Tested with Apache Johnzon:


<dependency>
    <groupId>org.apache.geronimo.specs</groupId>
    <artifactId>geronimo-jsonb_1.0_spec</artifactId>
    <version>1.4</version>
</dependency>
<dependency>
    <groupId>org.apache.geronimo.specs</groupId>
    <artifactId>geronimo-json_1.1_spec</artifactId>
    <version>1.5</version>
</dependency>
<dependency>
    <groupId>org.apache.johnzon</groupId>
    <artifactId>johnzon-jsonb</artifactId>
    <version>1.2.10</version>
</dependency>