{{announcement.body}}
{{announcement.title}}

Read/Write a Raw JSON, Array-Like JSON, and Map-Like JSON File as an Object

DZone 's Guide to

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.

· Java Zone ·
Free Resource

In 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:

Raw JSON vs array-like JSON vs map-like JSON

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:

Java
 




x


1
Path pathArray = Paths.get("melons_array.json");
2
Path pathMap = Paths.get("melons_map.json");
3
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:

Java
 




xxxxxxxxxx
1


 
1
public class Melon {
2
  private String type;
3
  private int weight;
4
      
5
  // getters and setters omitted for brevity
6
}



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:

Java
 




xxxxxxxxxx
1


 
1
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 :
Java
 




xxxxxxxxxx
1


1
Melon[] melonsArray = jsonb.fromJson(Files.newBufferedReader(
2
  pathArray, StandardCharsets.UTF_8), Melon[].class);



  • Let's read  melons_array.json  as a  List  of  Melon :
Java
 




xxxxxxxxxx
1


1
List<Melon> melonsList = jsonb.fromJson(Files.newBufferedReader(
2
    pathArray, StandardCharsets.UTF_8), ArrayList.class);



  • Let's read  melons_map.json  as a  Map  of  Melon :
Java
 




xxxxxxxxxx
1


 
1
Map<String, Melon> melonsMap = jsonb.fromJson(Files.newBufferedReader(
2
  pathMap, StandardCharsets.UTF_8), HashMap.class);



  • Let's read  melons_raw.json  line by line into a  Map :
Java
 




xxxxxxxxxx
1
10
9
10


 
1
Map<String, String> stringMap = new HashMap<>();
2
   
3
try (BufferedReader br = Files.newBufferedReader(pathRaw, StandardCharsets.UTF_8)) {
4
    
5
  String line;
6
  while ((line = br.readLine()) != null) {
7
    stringMap = jsonb.fromJson(line, HashMap.class);
8
    System.out.println("Current map is: " + stringMap);
9
  }
10
}



  • Let's read  melons_raw.json  line by line into a  Melon :
Java
 




xxxxxxxxxx
1


 
1
try (BufferedReader br = Files.newBufferedReader(pathRaw, StandardCharsets.UTF_8)) {
2
  
3
  String line;
4
  while ((line = br.readLine()) != null) {
5
    Melon melon = jsonb.fromJson(line, Melon.class);
6
    System.out.println("Current melon is: " + melon);
7
  }
8
}



  • Let's write an object into a JSON file ( melons_output.json ):
Java
 




xxxxxxxxxx
1


1
Path path = Paths.get("melons_output.json");
2
 
          
3
jsonb.toJson(melonsMap, Files.newBufferedWriter(path, StandardCharsets.UTF_8,
4
   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:

Java
 




xxxxxxxxxx
1


1
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 :
Java
 




xxxxxxxxxx
1


 
1
Melon[] melonsArray = mapper.readValue(Files.newBufferedReader(
2
  pathArray, StandardCharsets.UTF_8), Melon[].class);



  • Let's read  melons_array.json  as a  List  of  Melon :
Java
 




xxxxxxxxxx
1


 
1
List<Melon> melonsList = mapper.readValue(Files.newBufferedReader(
2
  pathArray, StandardCharsets.UTF_8), ArrayList.class);



  • Let's read  melons_map.json  as a  Map  of  Melon :
Java
 




xxxxxxxxxx
1


 
1
Map<String, Melon> melonsMap = mapper.readValue(Files.newBufferedReader(
2
  pathMap, StandardCharsets.UTF_8), HashMap.class);



  • Let's read  melons_raw.json  line by line into a  Map :
Java
 




xxxxxxxxxx
1
10
9
10
9
10
9
10
9
10
9
10
9
10


1
Map<String, String> stringMap = new HashMap<>();
2
  
3
try (BufferedReader br = Files.newBufferedReader(pathRaw, StandardCharsets.UTF_8)) {
4
   
5
  String line;
6
  while ((line = br.readLine()) != null) {
7
    stringMap = mapper.readValue(line, HashMap.class);
8
    System.out.println("Current map is: " + stringMap);
9
  }
10
}



  • Let's read  melons_raw.json  line by line into a  Melon :
Java
 




xxxxxxxxxx
1


1
try (BufferedReader br = Files.newBufferedReader(pathRaw, StandardCharsets.UTF_8)) {
2
     
3
  String line;
4
  while ((line = br.readLine()) != null) {
5
    Melon melon = mapper.readValue(line, Melon.class);
6
    System.out.println("Current melon is: " + melon);
7
  }
8
}



  • Let's write an object into a JSON file ( melons_output.json ):
Java
 




xxxxxxxxxx
1


1
Path path = Paths.get("melons_output.json");
2
   
3
mapper.writeValue(Files.newBufferedWriter(path, StandardCharsets.UTF_8,
4
  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 :

Java
 




xxxxxxxxxx
1


 
1
Gson gson = new Gson();



  • Let's read  melons_array.json  as an array of  Melon :
Java
 




xxxxxxxxxx
1


1
Melon[] melonsArray = gson.fromJson(
2
  Files.newBufferedReader(pathArray, StandardCharsets.UTF_8), Melon[].class);



  • Let's read  melons_array.json  as a  List  of  Melon :
Java
 




xxxxxxxxxx
1


1
List<Melon> melonsList = gson.fromJson(Files.newBufferedReader(
2
  pathArray, StandardCharsets.UTF_8), ArrayList.class);



  • Let's read  melons_map.json  as a  Map  of  Melon :
Java
 




xxxxxxxxxx
1


1
Map<String, Melon> melonsMap = gson.fromJson(Files.newBufferedReader(
2
  pathMap, StandardCharsets.UTF_8), HashMap.class);
3
    
4
// or, as TypeTolen, new TypeToken<HashMap<String, Melon>>() {}.getType()



  • Let's read  melons_raw.json  line by line into a  Map :
Java
 




xxxxxxxxxx
1
10
9
10
9
10
9
10
9
10
9
10
9
10


1
Map<String, String> stringMap = new HashMap<>();
2
  
3
try (BufferedReader br = Files.newBufferedReader(pathRaw, StandardCharsets.UTF_8)) {
4
    
5
  String line;
6
  while ((line = br.readLine()) != null) {
7
    stringMap = gson.fromJson(line, HashMap.class);
8
    System.out.println("Current map is: " + stringMap);
9
  }
10
}



  • Let's read  melons_raw.json  line by line into a  Melon :
Java
 




xxxxxxxxxx
1


1
try (BufferedReader br = Files.newBufferedReader(pathRaw, StandardCharsets.UTF_8)) {
2
    
3
  String line;
4
  while ((line = br.readLine()) != null) {
5
    Melon melon = gson.fromJson(line, Melon.class);
6
    System.out.println("Current melon is: " + melon);
7
  }
8
}



  • Let's write an object into a JSON file ( melons_output.json ):
Java
 




xxxxxxxxxx
1


 
1
Path path = Paths.get("melons_output.json");
2
    
3
gson.toJson(melonsMap, Files.newBufferedWriter(path, StandardCharsets.UTF_8,
4
   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! 

Topics:
gson ,jackson ,java ,json ,json api ,json array ,json-b ,tutorial

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}