In this Java Example I’ll use the same file which we have generated in previous tutorial.
Maven Dependency:
1 2 3 4 5 |
<dependency> <groupId>com.googlecode.json-simple</groupId> <artifactId>json-simple</artifactId> <version>1.1.1</version> </dependency> |
Previous Tutorial: https://crunchify.com/how-to-write-json-object-to-file-in-java/
Sample JSON file content:
1 2 3 4 5 6 7 8 9 |
{ "Name": "crunchify.com", "Author": "App Shah", "Company List": [ "Compnay: eBay", "Compnay: Paypal", "Compnay: Google" ] } |
CrunchifyJSONReadFromFile.java
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 |
package com.crunchify.tutorials; import java.io.FileReader; import java.util.Iterator; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; /** * @author Crunchify.com */ public class CrunchifyJSONReadFromFile { @SuppressWarnings("unchecked") public static void main(String[] args) { JSONParser parser = new JSONParser(); try { Object obj = parser.parse(new FileReader( "/Users/<username>/Documents/file1.txt")); JSONObject jsonObject = (JSONObject) obj; String name = (String) jsonObject.get("Name"); String author = (String) jsonObject.get("Author"); JSONArray companyList = (JSONArray) jsonObject.get("Company List"); System.out.println("Name: " + name); System.out.println("Author: " + author); System.out.println("\nCompany List:"); Iterator<String> iterator = companyList.iterator(); while (iterator.hasNext()) { System.out.println(iterator.next()); } } catch (Exception e) { e.printStackTrace(); } } } |
Other must read: Create and Deploy simple Web Service and Web Service Client in Eclipse
Output:
1 2 3 4 5 6 7 |
Name: Crunchify.com Author: App Shah Company List: Compnay: eBay Compnay: Paypal Compnay: Google |
Download json-simple-1.1.1.jar