Read/Write a Raw JSON, Array-Like JSON, and Map-Like JSON File as an Object
In this article, take a look at a tutorial that explains how to read/write a raw JSON, array-like JSON, and map-like JSON file as an object.
Join the DZone community and get the full member experience.
Join For FreeIn this article, you have a supersonic guide for reading/writing a JSON file via JSON-B, Jackson, and Gson.
Let's start with three text files that represent typical JSON-like mappings:
In melons_raw.json
, we have a JSON entry per line. Each line is a piece of JSON that's independent of the previous line but has the same schema. In melons_array.json
, we have a JSON array, and in melons_map.json
, we have a JSON that fits well in a Java Map
.
For each of these files, we have a Path
, as follows:
Path pathArray = Paths.get("melons_array.json");
Path pathMap = Paths.get("melons_map.json");
Path pathRaw = Paths.get("melons_raw.json");
Now let's take a look at three dedicated libraries for reading the contents of these files as Melon
instances:
xxxxxxxxxx
public class Melon {
private String type;
private int weight;
// getters and setters omitted for brevity
}
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:
xxxxxxxxxx
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 ofMelon
:
xxxxxxxxxx
Melon[] melonsArray = jsonb.fromJson(Files.newBufferedReader(
pathArray, StandardCharsets.UTF_8), Melon[].class);
- Let's read
melons_array.json
as aList
ofMelon
:
xxxxxxxxxx
List<Melon> melonsList = jsonb.fromJson(Files.newBufferedReader(
pathArray, StandardCharsets.UTF_8), ArrayList.class);
- Let's read
melons_map.json
as aMap
ofMelon
:
xxxxxxxxxx
Map<String, Melon> melonsMap = jsonb.fromJson(Files.newBufferedReader(
pathMap, StandardCharsets.UTF_8), HashMap.class);
- Let's read
melons_raw.json
line by line into aMap
:
xxxxxxxxxx
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 aMelon
:
xxxxxxxxxx
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
):
xxxxxxxxxx
Path path = Paths.get("melons_output.json");
jsonb.toJson(melonsMap, Files.newBufferedWriter(path, StandardCharsets.UTF_8,
StandardOpenOption.CREATE, StandardOpenOption.WRITE));
The complete code is available on GitHub.
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:
xxxxxxxxxx
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 ofMelon
:
xxxxxxxxxx
Melon[] melonsArray = mapper.readValue(Files.newBufferedReader(
pathArray, StandardCharsets.UTF_8), Melon[].class);
- Let's read
melons_array.json
as aList
ofMelon
:
xxxxxxxxxx
List<Melon> melonsList = mapper.readValue(Files.newBufferedReader(
pathArray, StandardCharsets.UTF_8), ArrayList.class);
- Let's read
melons_map.json
as aMap
ofMelon
:
xxxxxxxxxx
Map<String, Melon> melonsMap = mapper.readValue(Files.newBufferedReader(
pathMap, StandardCharsets.UTF_8), HashMap.class);
- Let's read
melons_raw.json
line by line into aMap
:
xxxxxxxxxx
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 aMelon
:
xxxxxxxxxx
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
):
xxxxxxxxxx
Path path = Paths.get("melons_output.json");
mapper.writeValue(Files.newBufferedWriter(path, StandardCharsets.UTF_8,
StandardOpenOption.CREATE, StandardOpenOption.WRITE), melonsMap);
The complete code is available on GitHub.
Using Gson
Gson is another fast library dedicated to processing (serializing/deserializing) JSON data. In a Maven project, it can be added as a dependency in pom.xml
. Its API relies on a class name, com.google.gson.Gson
:
xxxxxxxxxx
Gson gson = new Gson();
- Let's read
melons_array.json
as an array ofMelon
:
xxxxxxxxxx
Melon[] melonsArray = gson.fromJson(
Files.newBufferedReader(pathArray, StandardCharsets.UTF_8), Melon[].class);
- Let's read
melons_array.json
as aList
ofMelon
:
xxxxxxxxxx
List<Melon> melonsList = gson.fromJson(Files.newBufferedReader(
pathArray, StandardCharsets.UTF_8), ArrayList.class);
- Let's read
melons_map.json
as aMap
ofMelon
:
xxxxxxxxxx
Map<String, Melon> melonsMap = gson.fromJson(Files.newBufferedReader(
pathMap, StandardCharsets.UTF_8), HashMap.class);
// or, as TypeTolen, new TypeToken<HashMap<String, Melon>>() {}.getType()
- Let's read
melons_raw.json
line by line into aMap
:
xxxxxxxxxx
Map<String, String> stringMap = new HashMap<>();
try (BufferedReader br = Files.newBufferedReader(pathRaw, StandardCharsets.UTF_8)) {
String line;
while ((line = br.readLine()) != null) {
stringMap = gson.fromJson(line, HashMap.class);
System.out.println("Current map is: " + stringMap);
}
}
- Let's read
melons_raw.json
line by line into aMelon
:
xxxxxxxxxx
try (BufferedReader br = Files.newBufferedReader(pathRaw, StandardCharsets.UTF_8)) {
String line;
while ((line = br.readLine()) != null) {
Melon melon = gson.fromJson(line, Melon.class);
System.out.println("Current melon is: " + melon);
}
}
- Let's write an object into a JSON file (
melons_output.json
):
xxxxxxxxxx
Path path = Paths.get("melons_output.json");
gson.toJson(melonsMap, Files.newBufferedWriter(path, StandardCharsets.UTF_8,
StandardOpenOption.CREATE, StandardOpenOption.WRITE));
The complete code is available on GitHub.
If you enjoyed this article, then I'm sure you will love my book, Java Coding Problems, which has an entire chapter dedicated to Java I/O - Paths, files, buffers, scanning, and formatting. Check it out!
Opinions expressed by DZone contributors are their own.
Comments