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

Java 14 Record and Map.Entry

With a Java 14+ record:


import java.util.Map;

public record Developer(String language, int age) {
    public Developer(Map.Entry<String, Integer> entry) {
        this(entry.getKey(), entry.getValue());
    }
}

...an Map.Entry of Java's Map:

var developers = Map.of(
            "java", 25,
            "javascript", 24,
            "ruby", 30);

...can be directly converted into a record instance:

developers.entrySet().
            stream().
            map(Developer::new).
            forEach(System.out::println);

The snippet prints the following output:


Developer[language=java, age=25]
Developer[language=javascript, age=24]
Developer[language=ruby, age=30]

See it in action and from scratch in 3 minutes:

A Java Record can also come with additional methods / logic:


public record Developer(String language, int age) {
    //...
    public String nicerOutput() {
        return "I'm a " + this.language() + " developer and " + this.age() + " old";
    }
}

...and used inside the stream:


developers.entrySet().
            stream().
            map(Developer::new).
            map(Developer::nicerOutput).
            forEach(System.out::println);    

The code above prints:


I'm a javascript developer and 24 old
I'm a ruby developer and 30 old
I'm a java developer and 25 old    

What is the Direction of Quarkus?--an airhacks.fm podcast episode

Subscribe to airhacks.fm podcast via: spotify| iTunes| RSS

The #89 airhacks.fm episode with John Clingan (@jclingan) about:
MicroProfile, clouds, quarkus (support by RedHat) and quarkus "bottom up" approach, strategic goals and directions
is available for

Java 11: Write a String To File

With the method writeString introduced in Java 11, writing a String to a file takes a single line:


import static org.junit.jupiter.api.Assertions.assertEquals;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import org.junit.jupiter.api.Test;

//...

@Test
public void writeString() throws IOException {
    Path fileName = Path.of("celebration.txt");
    String content  = "duke is 25";
    Files.writeString(fileName, content);
    
    String actual = Files.readString(fileName);
    assertEquals(content,actual);
}

Java 14: A Simple Record

A Java record:


public record Article(String title, String content) {}    

...is a ready to use Data Transfer Object (DTO).

equals,hashCode, toString and private final field with corresponding accessors are generated as well.

The following code:


var article = new Article("java 14", "hello,record");
System.out.println("article = " + article + " " + article.content() + " " + article.title());

prints the following output:


article = Article[title=java 14, content=hello,record] hello,record java 14    

See it in action and "from scratch" in 4 mins:

Jakarta EE / MicroProfile / Web: Sessions, JUGs and Workshops

  1. Jakarta EE and MicroProfile: a Kickstart with reasonable Practices
    conference session JAX Online online 26 May 2020
  2. Productivity = Sustainability: How To Build Proper Backends in 2020 #noslides #nomigrations
    conference session devtalks conference online 12 Jun 2020
  3. Web For Java Devs
    JUG session JUG Switzerland online 25 Jun 2020
  4. building applications with native web components, redux and lit-html
    live virtual workshop https://airhacks.live online 9 Jul 2020

In-Process Polyglot with GraalVM--an airhacks.fm podcast episode

Subscribe to airhacks.fm podcast via: spotify| iTunes| RSS

The #88 airhacks.fm episode with Wolfgang Weigend (@wolflook) about:
GraalVM, polyglot programming, enterprise use cases, long term support and Java FX
is available for

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"
}    

If You Get A Book, You Have To Start Reading--an airhacks.fm podcast episode

Subscribe to airhacks.fm podcast via: spotify| iTunes| RSS

The #87 airhacks.fm episode with Max Rydahl Andersen (@maxandersen) about:
Hibernate contributions, IDE and tooling, Java, Modularization and Quarkus
is available for

Adding and Binding a Checkbox in a Web Component

Extending the form custom element (Web Component) and the state of the events application with a boolean property / checkbox element:

The application was built from scratch during the workshop: webcomponents-with-redux.training.

Online Workshops
...the last 150 posts
...the last 10 comments
License