Reading A JSON Configuration with JSON-B (Jakarta EE / MicroProfile) into a POJO

A configuration file:


{
    "connections":["first","next"],
    "user":"duke"
}    

...can be read into a Java POJO:


public class Configuration{
    public List<String> connections; 
    public String user;
    public int concurrency = 5; //default value    
}

...with (Jakarta EE's / MicroProfile's JSON-B) JsonbBuilder:


import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import jakarta.json.bind.JsonbBuilder;

//...

@Test
public void read() throws JsonbException, IOException {
    var location = Path.of("configuration.json");
    var reader = Files.newBufferedReader(location);
    var configuration = JsonbBuilder.create().fromJson(reader, Configuration.class);
    assertEquals(5,configuration.concurrency); //expecting default value
    assertEquals("duke", configuration.user);
    assertTrue(configuration.connections.contains("first"));
}

...and declaring the following dependency:


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

Comments:

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