How to read from json file in Java?

Reading from JSON Files in Java: A Step-by-Step Guide

Overview

JSON (JavaScript Object Notation) is a lightweight data interchange format that is widely used for exchanging data between web servers, web applications, and mobile applications. Java is a popular programming language that supports JSON out of the box, making it an ideal choice for building JSON-based applications. In this article, we will demonstrate how to read from a JSON file in Java.

Importing the necessary libraries

To read from a JSON file in Java, you will need to import the necessary libraries. Here is an example of how to import the JSON library:

import org.json.*;

You can also use the java.util.json package if you are using an older version of Java:

import java.util.*;
import java.util.json.*;

Parsing the JSON file

The org.json library provides a JsonReader class that can be used to parse a JSON file. Here is an example of how to parse a JSON file:

import org.json.*;

public class JsonFileReader {
public static void main(String[] args) throws Exception {
String filePath = "path/to/your/file.json";
String jsonContent = "{"name":"John","age":30,"city":"New York"}";

try (JsonReader reader = new JsonReader(new FileReader(filePath))) {
// Read the JSON content
// If the JSON content is valid, the following code will run
reader.read();

// Get the root object of the JSON data
ObjectMapper mapper = new ObjectMapper();
JsonNode root = mapper.readTree(jsonContent);

// Print the JSON data
System.out.println(root);
} catch (FileNotFoundException e) {
System.out.println("File not found: " + e.getMessage());
}
}
}

In this example, we use a try-with-resources statement to automatically close the JsonReader and ObjectMapper objects, regardless of whether an exception is thrown or not.

Deserializing the JSON data

Once the JSON content has been parsed, we can deserialize it into a Java object using the ObjectMapper class:

// Get the root object of the JSON data
JsonNode root = mapper.readTree(jsonContent);

// Convert the JSON data to an object
Person person = mapper.readValue(root, Person.class);

Here, we create a Person object from the parsed JSON data and use the ObjectMapper class to convert the JSON data to a Java object.

Common operations with JSON data

Here are some common operations that can be performed with JSON data:

  • Adding new data: We can use the add() method to add new data to the JSON object:
    person.add("city", "Chicago");
  • Updating an existing field: We can use the put() method to update an existing field in the JSON object:
    person.put("age", 31);
  • Removing an existing field: We can use the remove() method to remove an existing field from the JSON object:
    person.remove("city");
  • Finding an object by ID: We can use the find() method to find an object by its ID:
    person.find("id").put("name", "John");

Reading from external files

In addition to reading from local files, we can also read from external files using the FileReader class. Here is an example:

import java.io.*;

public class FileReader {
public static void main(String[] args) throws Exception {
String filePath = "path/to/your/file.json";
String jsonContent = "{"name":"John","age":30,"city":"New York"}";

try (FileReader reader = new FileReader(filePath)) {
// Read the JSON content
String jsonContentStr = reader.readLine();

// Convert the JSON content to a Java object
Person person = mapper.readValue(jsonContentStr, Person.class);

// Print the JSON data
System.out.println(person);
} catch (FileNotFoundException e) {
System.out.println("File not found: " + e.getMessage());
}
}
}

In this example, we use a try-with-resources statement to automatically close the FileReader object, regardless of whether an exception is thrown or not.

Conclusion

Reading from JSON files in Java is a straightforward process that can be performed using the org.json library. By following the steps outlined in this article, you can easily parse a JSON file, deserialize the data, and perform various operations on the JSON object.

Unlock the Future: Watch Our Essential Tech Videos!


Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top