Here is a simple Java tutorial which demonstrate how to parse JSONObject and JSONArrays in Java.
JSON syntax is a subset of the JavaScript object notation syntax:
- Data is in name/value pairs
- Data is separated by commas
- Curly braces hold objects
- Square brackets hold arrays
Just incase if you want to take a look at simple JSON tutorial which I’ve written sometime back. In this example we will read JSON File Crunchify_JSON.txt
from file system and then we will iterate through it.
In order to run below Java project, please add below Maven Dependency to your project in pom.xml file.
1 2 3 4 5 |
<dependency> <groupId>org.json</groupId> <artifactId>json</artifactId> <version>20151123</version> </dependency> |
Create this .txt file and update path in Java project:
1 2 3 4 5 6 7 8 9 |
{ "blogURL": "https://crunchify.com", "twitter": "https://twitter.com/Crunchify", "social": { "facebook": "http://facebook.com/Crunchify", "pinterest": "https://www.pinterest.com/Crunchify/crunchify-articles", "rss": "http://feeds.feedburner.com/Crunchify" } } |
Java Program:
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 |
package com.crunchify.tutorials; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import org.json.JSONException; import org.json.JSONObject; /** * @author Crunchify.com * */ public class CrunchifyParseJSONObject { public static void main(String[] args) throws FileNotFoundException, JSONException { String jsonData = ""; BufferedReader br = null; try { String line; br = new BufferedReader(new FileReader("/Users/<username>/Documents/Crunchify_JSON.txt")); while ((line = br.readLine()) != null) { jsonData += line + "\n"; } } catch (IOException e) { e.printStackTrace(); } finally { try { if (br != null) br.close(); } catch (IOException ex) { ex.printStackTrace(); } } // System.out.println("File Content: \n" + jsonData); JSONObject obj = new JSONObject(jsonData); System.out.println("blogURL: " + obj.getString("blogURL")); System.out.println("twitter: " + obj.getString("twitter")); System.out.println("social: " + obj.getJSONObject("social")); } } |
Result:
1 2 3 |
blogURL: https://crunchify.com twitter: https://twitter.com/Crunchify social: {"facebook":"http://facebook.com/Crunchify","rss":"http://feeds.feedburner.com/Crunchify","pinterest":"https://www.pinterest.com/Crunchify/crunchify-articles"} |