From Java Object to JSON and Back with Jakarta JSON Binding (JSON-B)

To use JSON-B (Jakarta JSON Binding) directly with a Java SE app, like e.g. JUnit, you will need to declare a single dependency:


<dependency>
    <groupId>org.eclipse</groupId>
    <artifactId>yasson</artifactId>
    <version>2.0.2</version>
</dependency>

Now a Java class:


import java.util.Date;

public class Workshop {
    public String title;
    public Date date;
    public String description;

}    

...can be serialized and deserialized with JSON-B:


import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

import airhacks.workshops.entity.Workshop;
import jakarta.json.bind.JsonbBuilder;
import jakarta.json.bind.JsonbConfig;


public interface Mapper {
    final static String FILE = "workshops.json";

    static void save(Workshop workshop) {
        var jsonb = JsonbBuilder.create(new JsonbConfig().withFormatting(true));
        try (var writer = new FileWriter(FILE)) {
            jsonb.toJson(workshop, writer);
        } catch (IOException ex) {
            throw new IllegalStateException(ex);
        }
    }

    static Workshop load() {
        try (var reader = new FileReader(FILE)) {
            return JsonbBuilder.create().fromJson(reader, Workshop.class);
        } catch (IOException ex) {
            throw new IllegalStateException(ex);
        }
    }
}    

...in a JUnit test:


import java.util.Date;

import org.junit.jupiter.api.Test;

public class JSONBTest {

    @Test
    public void serializeThenDeserialize() {
        var workshop = new Workshop();
        workshop.date = new Date();
        workshop.description = "no slides";
        workshop.title = "java and jakarta";

        Mapper.save(workshop);

        var copy = Mapper.load();
        assertEquals(workshop.title, copy.title);
    }

}    

...and the content of the workshops.json is:


{
    "date": "2021-10-03T05:25:42.168Z[UTC]",
    "description": "no slides",
    "title": "java and jakarta"
}

Comments:

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