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 {

    public void serialize() {
        var links = Set.of(new Link("json-b", ""),
                            new Link("jakarta ee", ""),
                            new Link("microprofile", ""));
        Jsonb jsonb = JsonbBuilder.create();
        var jsonArray = jsonb.toJson(links);

The code above generates the following output:

[{"text":"jakarta ee","uri":""},{"text":"microprofile","uri":""},{"text":"json-b","uri":""}]

Tested with Apache Johnzon:



Post a Comment:
  • HTML Syntax: NOT allowed
...the last 150 posts
...the last 10 comments