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
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workkloads.

Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • How To Check for JSON Insecure Deserialization (JID) Attacks With Java
  • Easy Mapping JSON to Java Objects Using Jackson
  • Writing DTOs With Java8, Lombok, and Java14+
  • Redefining Java Object Equality

Trending

  • Java’s Next Act: Native Speed for a Cloud-Native World
  • Issue and Present Verifiable Credentials With Spring Boot and Android
  • The 4 R’s of Pipeline Reliability: Designing Data Systems That Last
  • Event-Driven Architectures: Designing Scalable and Resilient Cloud Solutions
  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 user avatar
Anghel Leonard
DZone Core CORE ·
Apr. 22, 20 · Tutorial
Likes (6)
Comment
Save
Tweet
Share
27.2K Views

Join the DZone community and get the full member experience.

Join For Free

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
  • Easy Mapping JSON to Java Objects Using Jackson
  • Writing DTOs With Java8, Lombok, and Java14+
  • Redefining Java Object Equality

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

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 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!