Using JSON-B

Java EE 8 comes with a JAXB-like, declarative JSON binding called JSON-B (JSR-367). JSON-B is consistent with JAXB and other Java EE/SE APIs. Jakarta EE takes Java EE 8 JSON (P and B) to the next level. Its API is exposed via the javax.json.bind.Jsonb and javax.json.bind.JsonbBuilder classes:

Jsonb jsonb = JsonbBuilder.create();

For deserialization, we use Jsonb.fromJson(), while, for serialization, we use Jsonb.toJson():

  • Let's read melons_array.json as an Array of Melon:
Melon[] melonsArray = jsonb.fromJson(Files.newBufferedReader(
pathArray, StandardCharsets.UTF_8), Melon[].class);
  • Let's read melons_array.json as a List of Melon:
List<Melon> melonsList 
= jsonb.fromJson(Files.newBufferedReader(
pathArray, StandardCharsets.UTF_8), ArrayList.class);
  • Let's read melons_map.json as a Map of Melon:
Map<String, Melon> melonsMap 
= jsonb.fromJson(Files.newBufferedReader(
pathMap, StandardCharsets.UTF_8), HashMap.class);
  • Let's read melons_raw.json line by line into a Map:
Map<String, String> stringMap = new HashMap<>();

try (BufferedReader br = Files.newBufferedReader(
pathRaw, StandardCharsets.UTF_8)) {

String line;

while ((line = br.readLine()) != null) {
stringMap = jsonb.fromJson(line, HashMap.class);
System.out.println("Current map is: " + stringMap);
}
}
  • Let's read melons_raw.json line by line into a Melon:
try (BufferedReader br = Files.newBufferedReader(
pathRaw, StandardCharsets.UTF_8)) {

String line;

while ((line = br.readLine()) != null) {
Melon melon = jsonb.fromJson(line, Melon.class);
System.out.println("Current melon is: " + melon);
}
}
  • Let's write an object into a JSON file (melons_output.json):
Path path = Paths.get("melons_output.json");

jsonb.toJson(melonsMap, Files.newBufferedWriter(path,
StandardCharsets.UTF_8, StandardOpenOption.CREATE,
StandardOpenOption.WRITE));
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset