How to Read JSON File in Java: Simple Example and Syntax
To read a
JSON file in Java, use a library like Jackson or Gson. Load the file as a stream or string, then parse it into Java objects using the library's methods.Syntax
Here is the basic syntax to read a JSON file using the Jackson library:
ObjectMapper: Main class to map JSON to Java objects.readValue(File, Class): Reads JSON from a file and converts it to the specified Java class.
java
ObjectMapper mapper = new ObjectMapper(); MyClass obj = mapper.readValue(new File("file.json"), MyClass.class);
Example
This example shows how to read a JSON file named data.json into a Java class Person using Jackson.
java
import com.fasterxml.jackson.databind.ObjectMapper; import java.io.File; class Person { public String name; public int age; @Override public String toString() { return "Person{name='" + name + "', age=" + age + "}"; } } public class ReadJsonExample { public static void main(String[] args) { try { ObjectMapper mapper = new ObjectMapper(); Person person = mapper.readValue(new File("data.json"), Person.class); System.out.println(person); } catch (Exception e) { e.printStackTrace(); } } }
Output
Person{name='Alice', age=30}
Common Pitfalls
- Not including the JSON library (like Jackson) in your project dependencies causes
ClassNotFoundException. - Incorrect file path leads to
FileNotFoundException. - Mismatch between JSON structure and Java class fields causes parsing errors.
- Forgetting to handle exceptions can crash your program.
java
/* Wrong: Missing try-catch and wrong file path */ ObjectMapper mapper = new ObjectMapper(); Person person = mapper.readValue(new File("wrong_path.json"), Person.class); /* Right: Use try-catch and correct file path */ try { ObjectMapper mapper = new ObjectMapper(); Person person = mapper.readValue(new File("data.json"), Person.class); } catch (Exception e) { e.printStackTrace(); }
Quick Reference
| Step | Description |
|---|---|
| Add Jackson dependency | Include com.fasterxml.jackson.core:jackson-databind in your project. |
| Create Java class | Define a class matching your JSON structure. |
| Create ObjectMapper | Instantiate ObjectMapper to handle JSON. |
| Read JSON file | Use readValue() to parse JSON into Java object. |
| Handle exceptions | Use try-catch to manage IO and parsing errors. |
Key Takeaways
Use Jackson's ObjectMapper to read JSON files easily in Java.
Ensure your Java class matches the JSON structure for correct parsing.
Always handle exceptions like IOException and JsonProcessingException.
Include the Jackson library in your project dependencies before running.
Verify the JSON file path is correct to avoid file not found errors.