DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • How To Check for JSON Insecure Deserialization (JID) Attacks With Java
  • Apache Spark 3 to Apache Spark 4 Migration: What Breaks, What Improves, What's Mandatory
  • Writing DTOs With Java8, Lombok, and Java14+
  • Redefining Java Object Equality

Trending

  • Agentic Test Creation: From Plain-Language Requirements to End-to-End Test Cases
  • Building IoT Time-Series Applications With Java and Apache IoTDB
  • Event Sourcing in Distributed Systems: Architecture, Consistency, and Fault-Tolerant Projections
  • How to Build Your Own AI SRE From Scratch

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  1. DZone
  2. Coding
  3. Languages
  4. Read/Write a Raw JSON, Array-Like JSON, and Map-Like JSON File as an Object

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.

By 
Anghel Leonard
DZone Core CORE ·
Apr. 22, 20 · Tutorial
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
28.3K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

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! 

JSON Java (programming language) Object (computer science)

Opinions expressed by DZone contributors are their own.

Related

  • How To Check for JSON Insecure Deserialization (JID) Attacks With Java
  • Apache Spark 3 to Apache Spark 4 Migration: What Breaks, What Improves, What's Mandatory
  • Writing DTOs With Java8, Lombok, and Java14+
  • Redefining Java Object Equality

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook