Gson read and parse JSON file example shows how to read JSON file and parse it using the Gson library in Java. This example also shows how to read various fields from the JSON file.
How to read JSON file using Gson in Java?
Reading a JSON file in Java is no different than reading any other type of file. However, once the JSON file content is read, we need to parse it as well before we can access any data from it.
Here is the employee.json file we are going to use for this example.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
{ "Id": "EMP001", "Name": "Alex", "Age": 22, "IsManager": false, "ReservedParking": null, "Languages": ["English", "Spanish"], "Experience": [ { "CompanyName": "ABC Ltd.", "Years": 2.5 }, { "CompanyName": "XYZ Ltd.", "Years": 3 } ] } |
We start with reading the JSON file using the BufferedReader class. Once we get the reader, we can use the fromJson
method to create a JsonObject from the file content as given below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 |
package com.javacodeexamples.gsonexamples; import java.io.BufferedReader; import java.io.FileReader; import com.google.gson.Gson; import com.google.gson.JsonObject; public class GsonReadJsonFileExample { public static void main(String[] args) { //file path String strFilePath = "D:\\employee.json"; //create a reader to read the file try (BufferedReader reader = new BufferedReader(new FileReader(strFilePath))) { //create JsonObject from the JSON file content JsonObject jsonObject = new Gson().fromJson(reader, JsonObject.class); System.out.println("JSON file data: " + jsonObject); /* * Once we get the JsonObject, we * can aceess its properties using the * get methods */ //get string data System.out.println("Name: " + jsonObject.get("Name").getAsString()); //get boolean value System.out.println("Is Manager? " + jsonObject.get("IsManager").getAsBoolean()); //get int data System.out.println("Age: " + jsonObject.get("Age").getAsInt()); //get language array property System.out.println("Json language Array: " + jsonObject.get("Languages").getAsJsonArray()); //get first company's years of experience as a double value System.out.println("Years of experience: " + jsonObject.get("Experience").getAsJsonArray() .get(0).getAsJsonObject() .get("Years").getAsDouble()); } catch (Exception e) { e.printStackTrace(); } } } |
Output
1 2 3 4 5 6 |
JSON file data: {"Id":"EMP001","Name":"Alex","Age":22,"IsManager":false,"ReservedParking":null,"Languages":["English","Spanish"],"Experience":[{"CompanyName":"ABC Ltd.","Years":2.5},{"CompanyName":"XYZ Ltd.","Years":3}]} Name: Alex Is Manager? false Age: 22 Json language Array: ["English","Spanish"] Years of experience: 2.5 |
Now, instead of converting the JSON file to a JsonObject using the fromJson
method, we can also convert it to a Pojo object.
Please let me know your views in the comments section below.