Java 14+: Java Record JSON Serialization and Deserialization with JSON-B

To serialize a Java 14 POJR (Plain Old Java Record):

public record Developer(int age, String language) {
You can use stock JSON-B Jakarta EE API:

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

public class JavaTest {

    public void jsonb() {
        Jsonb jsonb = JsonbBuilder.create();
        var developer = new Developer(25, "java");
        var serialized = jsonb.toJson(developer);
        System.out.println("serialized = " + serialized);
        var clone = jsonb.fromJson(serialized, Developer.class);
        System.out.println("clone = " + clone);

Java Record serialization might be not available with all SPI implementations. However, Apache Johnzon supports it out-of-the-box:


See it in action and from scratch in 3 mins:

The above unit test generates the following output:

serialized = {"age":25,"language":"java"}
clone = Developer[age=0, language=null]    
Thanks to @rmannibucau for the commits :-)


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