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 {

    @Test
    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:


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

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 :-)

Comments:

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