Using Jackson

Jackson is a popular and fast library dedicated to processing (serializing/deserializing) JSON data. The Jackson API relies on  com.fasterxml.jackson.databind.ObjectMapper. Let's go over the preceding examples again, but this time using Jackson:

ObjectMapper mapper = new ObjectMapper();

For deserialization, we use ObjectMapper.readValue(), while for serialization, we use ObjectMapper.writeValue():

  • Let's read melons_array.json as an Array of Melon:
Melon[] melonsArray 
= mapper.readValue(Files.newBufferedReader(
pathArray, StandardCharsets.UTF_8), Melon[].class);
  • Let's read melons_array.json as a List of Melon:
List<Melon> melonsList 
= mapper.readValue(Files.newBufferedReader(
pathArray, StandardCharsets.UTF_8), ArrayList.class);
  • Let's read melons_map.json as a Map of Melon:
Map<String, Melon> melonsMap 
= mapper.readValue(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 = mapper.readValue(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 = mapper.readValue(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");

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

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