
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.
<dependency> <groupId>org.json</groupId> <artifactId>json</artifactId> <version>20151123</version> </dependency>
Example-1.
Create this .txt file and update path in Java project:
{
"blogURL": "https://crunchify.com",
"twitter": "https://twitter.com/Crunchify",
"social": {
"facebook": "http://facebook.com/Crunchify",
"pinterest": "https://www.pinterest.com/Crunchify/crunchify-articles",
"rss": "https://crunchify.com/feed/"
}
}
Java Program:
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:
blogURL: https://crunchify.com
twitter: https://twitter.com/Crunchify
social: {"facebook":"http://facebook.com/Crunchify","rss":"https://crunchify.com/feed/","pinterest":"https://www.pinterest.com/Crunchify/crunchify-articles"}
Example-2.
Here is a complete Java program that demonstrates parsing both JSON objects and arrays.
CrunchifyParseJsonObjectAndArray.java
package crunchify.com.java.tutorials;
import org.json.JSONArray;
import org.json.JSONObject;
/**
* @author Crunchify.com
* Program: How to Parse JSONObject and JSONArrays in Java? Beginner's Guide
*
*/
public class CrunchifyParseJsonObjectAndArray {
public static void main(String[] args) {
// JSON object string
String jsonObjectString = "{\"name\":\"Crunchify\",\"year\":2023,\"city\":\"New York\"}";
// Parse the JSON object string into a JSONObject
JSONObject jsonObject = new JSONObject(jsonObjectString);
// Extract values from the JSON object
String name = jsonObject.getString("name");
int year = jsonObject.getInt("year");
String city = jsonObject.getString("city");
// Print the values
System.out.println("Name: " + name);
System.out.println("Year: " + year);
System.out.println("City: " + city);
System.out.println();
// JSON array string
String jsonArrayString = "[{\"name\":\"Crunchify\",\"year\":2022,\"city\":\"London\"},{\"name\":\"Google\",\"year\":2022,\"city\":\"Paris\"}]";
// Parse the JSON array string into a JSONArray
JSONArray jsonArray = new JSONArray(jsonArrayString);
// Loop through the JSONArray to extract values from each JSON object
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = jsonArray.getJSONObject(i);
name = object.getString("name");
year = object.getInt("year");
city = object.getString("city");
System.out.println("Name: " + name);
System.out.println("Year: " + year);
System.out.println("City: " + city);
}
}
}
IntelliJ IDEA Result
Just run above program as a Java Application and you should see result as below.
Name: Crunchify Year: 2023 City: New York Name: Crunchify Year: 2022 City: London Name: Google Year: 2022 City: Paris Process finished with exit code 0
Details:
- The first step is to import the
org.json.JSONObjectandorg.json.JSONArrayclasses, which are part of the org.json library. - Then, we define a
jsonObjectStringvariable, which holds a string representation of a JSON object. - Using the
JSONObjectclass, we parse thejsonObjectStringinto aJSONObjectusing thenew JSONObject(jsonObjectString)constructor. - Then, we use the
getString,getInt, andgetBooleanmethods to extract values from thejsonObject. - After printing out the values, we do a similar process to parse a
jsonArrayStringinto aJSONArrayand loop through each JSON object to extract and print values.


How to get the data if we have something like this “alerts”: [{
“id”: “PIA82T5”,
“service”: {
“id”: “PQZOKCF”,
},
“severity”: “info”,
“incident”: {
“id”: “PURF3KP”,
“body”: {
“contexts”: [],
“details”: {
“Alert Message”: “Recorded values are above the threshold for Net_Byte_per_sec_15”,
}
How to get the details data
Hi Amit Lodhi – basically you want to parse above data – right? If yes, try looking at this tutorial with all details: https://crunchify.com/how-to-use-gson-fromjson-to-convert-the-specified-json-into-an-object-of-the-specified-class/
(Not JSON comment) Why do you need to read the file line by line and then glue them back together? You can read the whole file content at once.
Hi Dusan Sormaz – that’s correct we can absolutely do that. Please visit detailed tutorial for the same: https://crunchify.com/how-to-read-complete-file-at-a-once-in-java-without-using-any-loop/
Let me know if you have any more questions.
I want to get tweets from twitter rest api and want to write in file …. I dont know how to do this in java… I’ll be thankful if anyone will help me.
{ "statuses": [ { "created_at": "Wed Apr 12 04:53:25 +0000 2017", "id": 852021818290352129, "id_str": "852021818290352129", "text": "Watch NASA's first 4K broadcast from space on April 26th - Engadget https:\/\/t.co\/EfwAYeJpjF", "truncated": false, "entities": { "hashtags": [ ], "symbols": [ ], "user_mentions": [ ], "urls": [ { "url": "https:\/\/t.co\/EfwAYeJpjF", "expanded_url": "http:\/\/ift.tt\/2orifBN", "display_url": "ift.tt\/2orifBN", "indices": [ 68, 91 ] } ] }, "metadata": { "iso_language_code": "en", "result_type": "recent" }, "source": "<a href="https:\/\/ifttt.com" rel="nofollow ugc">IFTTT", "in_reply_to_status_id": null, "in_reply_to_status_id_str": null, "in_reply_to_user_id": null, "in_reply_to_user_id_str": null, "in_reply_to_screen_name": null, "user": { "id": 622857704, "id_str": "622857704", "name": "Crucial-Tech", "screen_name": "crucial_tech", "location": "Worldwide", "description": "Technology News | Stories | Solutions | Workarounds | Gadgets", "url": null, "entities": { "description": { "urls": [ ] } }, "protected": false, "followers_count": 1917, "friends_count": 841, "listed_count": 513, "created_at": "Sat Jun 30 14:28:07 +0000 2012", "favourites_count": 33, "utc_offset": -14400, "time_zone": "Eastern Time (US & Canada)", "geo_enabled": true, "verified": false, "statuses_count": 559097, "lang": "en", "contributors_enabled": false, "is_translator": false, "is_translation_enabled": false, "profile_background_color": "131516", "profile_background_image_url": "http:\/\/pbs.twimg.com\/profile_background_images\/530442443057942528\/jgQgrriz.jpeg", "profile_background_image_url_https": "https:\/\/pbs.twimg.com\/profile_background_images\/530442443057942528\/jgQgrriz.jpeg", "profile_background_tile": true, "profile_image_url": "http:\/\/pbs.twimg.com\/profile_images\/810537113288482816\/AL7srBp3_normal.jpg", "profile_image_url_https": "https:\/\/pbs.twimg.com\/profile_images\/810537113288482816\/AL7srBp3_normal.jpg", "profile_banner_url": "https:\/\/pbs.twimg.com\/profile_banners\/622857704\/1415224702", "profile_link_color": "3B94D9", "profile_sidebar_border_color": "000000", "profile_sidebar_fill_color": "000000", "profile_text_color": "000000", "profile_use_background_image": true, "has_extended_profile": false, "default_profile": false, "default_profile_image": false, "following": false, "follow_request_sent": false, "notifications": false, "translator_type": "none" }, "geo": null, "coordinates": null, "place": null, "contributors": null, "is_quote_status": false, "retweet_count": 0, "favorite_count": 0, "favorited": false, "retweeted": false, "possibly_sensitive": false, "lang": "en" }, { "created_at": "Wed Apr 12 04:53:08 +0000 2017", "id": 8.5202174412671e+17, "id_str": "852021744126705664", "text": "RT @TechCrunch: NASA and Amazon will stream from space in 4K for the first time on April 26 https:\/\/t.co\/KWMfvRg1Hs", "truncated": false, "entities": { "hashtags": [ ], "symbols": [ ], "user_mentions": [ { "screen_name": "TechCrunch", "name": "TechCrunch", "id": 816653, "id_str": "816653", "indices": [ 3, 14 ] } ], "urls": [ { "url": "https:\/\/t.co\/KWMfvRg1Hs", "expanded_url": "http:\/\/tcrn.ch\/2nB1aGU", "display_url": "tcrn.ch\/2nB1aGU", "indices": [ 92, 115 ] } ] }, "metadata": { "iso_language_code": "en", "result_type": "recent" }, "source": "</a><a href="http:\/\/twitter.com\/download\/iphone" rel="nofollow ugc">Twitter for iPhone", "in_reply_to_status_id": null, "in_reply_to_status_id_str": null, "in_reply_to_user_id": null, "in_reply_to_user_id_str": null, "in_reply_to_screen_name": null, "user": { "id": 18961853, "id_str": "18961853", "name": "Hongik Kim", "screen_name": "nottora2", "location": "Seoul, Korea", "description": "", "url": "http:\/\/t.co\/WpOh7jvYit", "entities": { "url": { "urls": [ { "url": "http:\/\/t.co\/WpOh7jvYit", "expanded_url": "http:\/\/sttora2.net", "display_url": "sttora2.net", "indices": [ 0, 22 ] } ] }, "description": { "urls": [ ] } }, "protected": false, "followers_count": 713, "friends_count": 232, "listed_count": 255, "created_at": "Wed Jan 14 01:17:32 +0000 2009", "favourites_count": 14, "utc_offset": -36000, "time_zone": "Hawaii", "geo_enabled": true, "verified": false, "statuses_count": 45276, "lang": "en", "contributors_enabled": false, "is_translator": false, "is_translation_enabled": false, "profile_background_color": "1A1B1F", "profile_background_image_url": "http:\/\/abs.twimg.com\/images\/themes\/theme9\/bg.gif", "profile_background_image_url_https": "https:\/\/abs.twimg.com\/images\/themes\/theme9\/bg.gif", "profile_background_tile": false, "profile_image_url": "http:\/\/pbs.twimg.com\/profile_images\/420186574\/0001_normal.jpg", "profile_image_url_https": "https:\/\/pbs.twimg.com\/profile_images\/420186574\/0001_normal.jpg", "profile_link_color": "2FC2EF", "profile_sidebar_border_color": "181A1E", "profile_sidebar_fill_color": "252429", "profile_text_color": "666666", "profile_use_background_image": true, "has_extended_profile": false, "default_profile": false, "default_profile_image": false, "following": false, "follow_request_sent": false, "notifications": false, "translator_type": "none" }, "geo": null, "coordinates": null, "place": null, "contributors": null, "retweeted_status": { "created_at": "Wed Apr 12 01:48:02 +0000 2017", "id": 8.5197516353722e+17, "id_str": "851975163537219585", "text": "NASA and Amazon will stream from space in 4K for the first time on April 26 https:\/\/t.co\/KWMfvRg1Hs", "truncated": false, "entities": { "hashtags": [ ], "symbols": [ ], "user_mentions": [ ], "urls": [ { "url": "https:\/\/t.co\/KWMfvRg1Hs", "expanded_url": "http:\/\/tcrn.ch\/2nB1aGU", "display_url": "tcrn.ch\/2nB1aGU", "indices": [ 76, 99 ] } ] }, "metadata": { "iso_language_code": "en", "result_type": "recent" }, "source": "</a><a href="http:\/\/www.socialflow.com" rel="nofollow ugc">SocialFlow", "in_reply_to_status_id": null, "in_reply_to_status_id_str": null, "in_reply_to_user_id": null, "in_reply_to_user_id_str": null, "in_reply_to_screen_name": null, "user": { "id": 816653, "id_str": "816653", "name": "TechCrunch", "screen_name": "TechCrunch", "location": "San Francisco, CA", "description": "Breaking technology news, analysis, and opinions from TechCrunch. The number one guide for all things tech. Got a tip? Let us know tips@techcrunch.com", "url": "https:\/\/t.co\/b5Oyx12qGG", "entities": { "url": { "urls": [ { "url": "https:\/\/t.co\/b5Oyx12qGG", "expanded_url": null, "indices": [ 0, 23 ] } ] }, "description": { "urls": [ ] } }, "protected": false, "followers_count": 8841742, "friends_count": 900, "listed_count": 108869, "created_at": "Wed Mar 07 01:27:09 +0000 2007", "favourites_count": 1911, "utc_offset": -25200, "time_zone": "Pacific Time (US & Canada)", "geo_enabled": true, "verified": true, "statuses_count": 153722, "lang": "en", "contributors_enabled": false, "is_translator": false, "is_translation_enabled": true, "profile_background_color": "149500", "profile_background_image_url": "http:\/\/pbs.twimg.com\/profile_background_images\/621096023751004161\/BAKy7hCT.png", "profile_background_image_url_https": "https:\/\/pbs.twimg.com\/profile_background_images\/621096023751004161\/BAKy7hCT.png", "profile_background_tile": false, "profile_image_url": "http:\/\/pbs.twimg.com\/profile_images\/615392662233808896\/EtxjSSKk_normal.jpg", "profile_image_url_https": "https:\/\/pbs.twimg.com\/profile_images\/615392662233808896\/EtxjSSKk_normal.jpg", "profile_banner_url": "https:\/\/pbs.twimg.com\/profile_banners\/816653\/1490894597", "profile_link_color": "097000", "profile_sidebar_border_color": "FFFFFF", "profile_sidebar_fill_color": "DDFFCC", "profile_text_color": "222222", "profile_use_background_image": true, "has_extended_profile": false, "default_profile": false, "default_profile_image": false, "following": false, "follow_request_sent": false, "notifications": false, "translator_type": "none" }, "geo": null, "coordinates": null, "place": null, "contributors": null, "is_quote_status": false, "retweet_count": 132, "favorite_count": 156, "favorited": false, "retweeted": false, "possibly_sensitive": false, "lang": "en" }, "is_quote_status": false, "retweet_count": 132, "favorite_count": 0, "favorited": false, "retweeted": false, "possibly_sensitive": false, "lang": "en" }, { "created_at": "Wed Apr 12 04:52:50 +0000 2017", "id": 8.5202166885153e+17, "id_str": "852021668851531776", "text": "RT @snowdenka: cool down\nturnin' up\nforever\nreal\nthe life\ni love to love you\nuntitled (based from bret's story)\n\neto yung alam natin na nas\u2026", "truncated": false, "entities": { "hashtags": [ ], "symbols": [ ], "user_mentions": [ { "screen_name": "snowdenka", "name": "\u2744 Macy \u270b\ud83d\udca4\u2728", "id": 2330241865, "id_str": "2330241865", "indices": [ 3, 13 ] } ], "urls": [ ] }, "metadata": { "iso_language_code": "en", "result_type": "recent" }, "source": "</a><a href="http:\/\/twitter.com\/download\/android" rel="nofollow ugc">Twitter for Android", "in_reply_to_status_id": null, "in_reply_to_status_id_str": null, "in_reply_to_user_id": null, "in_reply_to_user_id_str": null, "in_reply_to_screen_name": null, "user": { "id": 2433542798, "id_str": "2433542798", "name": "\u256e(\u2500\u25bd\u2500)\u256d", "screen_name": "hallowjayn", "location": "shyschai", "description": "I can tweet whatever I want. It's my twitter.", "url": null, "entities": { "description": { "urls": [ ] } }, "protected": false, "followers_count": 697, "friends_count": 217, "listed_count": 7, "created_at": "Tue Apr 08 12:29:46 +0000 2014", "favourites_count": 6775, "utc_offset": -25200, "time_zone": "Pacific Time (US & Canada)", "geo_enabled": true, "verified": false, "statuses_count": 37632, "lang": "en", "contributors_enabled": false, "is_translator": false, "is_translation_enabled": false, "profile_background_color": "89C9FA", "profile_background_image_url": "http:\/\/pbs.twimg.com\/profile_background_images\/618681903441252352\/rjLy48Ga.jpg", "profile_background_image_url_https": "https:\/\/pbs.twimg.com\/profile_background_images\/618681903441252352\/rjLy48Ga.jpg", "profile_background_tile": true, "profile_image_url": "http:\/\/pbs.twimg.com\/profile_images\/851045496906854400\/z1iIPlRm_normal.jpg", "profile_image_url_https": "https:\/\/pbs.twimg.com\/profile_images\/851045496906854400\/z1iIPlRm_normal.jpg", "profile_banner_url": "https:\/\/pbs.twimg.com\/profile_banners\/2433542798\/1491546365", "profile_link_color": "9266CC", "profile_sidebar_border_color": "5ED4DC", "profile_sidebar_fill_color": "95E8EC", "profile_text_color": "3C3940", "profile_use_background_image": true, "has_extended_profile": true, "default_profile": false, "default_profile_image": false, "following": false, "follow_request_sent": false, "notifications": false, "translator_type": "none" }, "geo": null, "coordinates": null, "place": null, "contributors": null, "retweeted_status": { "created_at": "Tue Apr 11 15:16:25 +0000 2017", "id": 8.5181621006066e+17, "id_str": "851816210060660737", "text": "cool down\nturnin' up\nforever\nreal\nthe life\ni love to love you\nuntitled (based from bret's story)\n\neto yung alam natin na nasa palm dreams.", "truncated": false, "entities": { "hashtags": [ ], "symbols": [ ], "user_mentions": [ ], "urls": [ ] }, "metadata": { "iso_language_code": "en", "result_type": "recent" }, "source": "</a><a href="http:\/\/twitter.com\/download\/android" rel="nofollow ugc">Twitter for Android", "in_reply_to_status_id": null, "in_reply_to_status_id_str": null, "in_reply_to_user_id": null, "in_reply_to_user_id_str": null, "in_reply_to_screen_name": null, "user": { "id": 2330241865, "id_str": "2330241865", "name": "\u2744 Macy \u270b\ud83d\udca4\u2728", "screen_name": "snowdenka", "location": "", "description": "JaDine, Harry Potter, JPop, Anime | fangirling. fanworks. random thoughts. kalokohan. whinings about life | IG: jadinex \u2022 YT: JaDinex \u2022 WP: kooridenka", "url": "https:\/\/t.co\/UqnYe2vdrc", "entities": { "url": { "urls": [ { "url": "https:\/\/t.co\/UqnYe2vdrc", "expanded_url": "http:\/\/jadinex.livejournal.com", "display_url": "jadinex.livejournal.com", "indices": [ 0, 23 ] } ] }, "description": { "urls": [ ] } }, "protected": false, "followers_count": 2962, "friends_count": 244, "listed_count": 34, "created_at": "Thu Feb 06 12:41:08 +0000 2014", "favourites_count": 39812, "utc_offset": -25200, "time_zone": "Pacific Time (US & Canada)", "geo_enabled": false, "verified": false, "statuses_count": 102431, "lang": "en", "contributors_enabled": false, "is_translator": false, "is_translation_enabled": false, "profile_background_color": "000000", "profile_background_image_url": "http:\/\/abs.twimg.com\/images\/themes\/theme1\/bg.png", "profile_background_image_url_https": "https:\/\/abs.twimg.com\/images\/themes\/theme1\/bg.png", "profile_background_tile": false, "profile_image_url": "http:\/\/pbs.twimg.com\/profile_images\/845930850210361344\/fgHcvMFy_normal.jpg", "profile_image_url_https": "https:\/\/pbs.twimg.com\/profile_images\/845930850210361344\/fgHcvMFy_normal.jpg", "profile_banner_url": "https:\/\/pbs.twimg.com\/profile_banners\/2330241865\/1491408790", "profile_link_color": "DD2E44", "profile_sidebar_border_color": "000000", "profile_sidebar_fill_color": "000000", "profile_text_color": "000000", "profile_use_background_image": false, "has_extended_profile": true, "default_profile": false, "default_profile_image": false, "following": false, "follow_request_sent": false, "notifications": false, "translator_type": "none" }, "geo": null, "coordinates": null, "place": null, "contributors": null, "is_quote_status": false, "retweet_count": 61, "favorite_count": 70, "favorited": false, "retweeted": false, "lang": "en" }, "is_quote_status": false, "retweet_count": 61, "favorite_count": 0, "favorited": false, "retweeted": false, "lang": "en" } ], "search_metadata": { "completed_in": 0.034, "max_id": 8.5202181829035e+17, "max_id_str": "852021818290352129", "query": "from%253ANasa%2520OR%2520%2523nasa", "refresh_url": "?since_id=852021818290352129&q=from%253ANasa%2520OR%2520%2523nasa&include_entities=1", "count": 15, "since_id": 0, "since_id_str": "0" } } </a>Hi Hassaan – it seems like want to read above JSON and parse it. Try looking at this tutorial with more details: https://crunchify.com/json-manipulation-in-java-examples/
Feel free to ping me for any exception you get. I’ll try to help you get it work.
Hi!
How should I parse this kind of file:
{ "took" : 21, "timed_out" : false, "_shards" : { "total" : 35, "successful" : 35, "failed" : 0 }, "hits" : { "total" : 38031, "max_score" : 1.0, "hits" : [ { "_index" : "packetbeat-2017.12.12", "_type" : "flow", "_id" : "AWBKxeKQ4UR9vnvGp98V", "_score" : 1.0, "_source" : { "source" : { "port" : 44880, "stats" : { "net_bytes_total" : 6064, "net_packets_total" : 48 }, "ip" : "192.168.200.202" }, "transport" : "tcp", "type" : "flow", "dest" : { "port" : 9200, "stats" : { "net_bytes_total" : 7376, "net_packets_total" : 32 }, "ip" : "192.168.200.202" }, "tags" : [ "beats_input_raw_event" ], "start_time" : "2017-12-12T12:49:10.852Z", "@timestamp" : "2017-12-12T12:49:30.000Z", "flow_id" : "EAT/////AP//////CP8AAAHAqMjKwKjIylCv8CM", "last_time" : "2017-12-12T12:49:10.852Z", "final" : false, "beat" : { "hostname" : "ubuntu", "name" : "ubuntu", "version" : "5.4.1" }, "@version" : "1", "host" : "ubuntu" } }, { "_index" : "packetbeat-2017.12.12", "_type" : "flow", "_id" : "AWBKxeKQ4UR9vnvGp98Y", "_score" : 1.0, "_source" : { "transport" : "tcp", "source" : { "port" : 50294, "stats" : { "net_bytes_total" : 124, "net_packets_total" : 2 }, "ip" : "192.168.200.1" }, "type" : "flow", "dest" : { "port" : 9200, "stats" : { "net_bytes_total" : 136, "net_packets_total" : 2 }, "ip" : "192.168.200.202" }, "tags" : [ "beats_input_raw_event" ], "start_time" : "2017-12-12T12:49:19.325Z", "@timestamp" : "2017-12-12T12:49:30.000Z", "flow_id" : "EAT/////AP//////CP8AAAHAqMgBwKjIynbE8CM", "last_time" : "2017-12-12T12:49:19.325Z", "final" : false, "beat" : { "hostname" : "ubuntu", "name" : "ubuntu", "version" : "5.4.1" }, "@version" : "1", "host" : "ubuntu" } }, { "_index" : "packetbeat-2017.12.12", "_type" : "flow", "_id" : "AWBKxjCT4UR9vnvGp98k", "_score" : 1.0, "_source" : { "transport" : "tcp", "source" : { "stats" : { "net_bytes_total" : 21274, "net_packets_total" : 24 }, "port" : 44882, "ip" : "192.168.200.202" }, "type" : "flow", "dest" : { "port" : 9200, "stats" : { "net_bytes_total" : 5996, "net_packets_total" : 17 }, "ip" : "192.168.200.202" }, "tags" : [ "beats_input_raw_event" ], "start_time" : "2017-12-12T12:49:10.776Z", "@timestamp" : "2017-12-12T12:49:50.000Z", "last_time" : "2017-12-12T12:49:10.776Z", "flow_id" : "EAT/////AP//////CP8AAAHAqMjKwKjIylKv8CM", "final" : false, "beat" : { "hostname" : "ubuntu", "name" : "ubuntu", "version" : "5.4.1" }, "@version" : "1", "host" : "ubuntu" } }, { "_index" : "packetbeat-2017.12.12", "_type" : "flow", "_id" : "AWBKxjCT4UR9vnvGp98m", "_score" : 1.0, "_source" : { "source" : { "port" : 44878, "stats" : { "net_bytes_total" : 15792, "net_packets_total" : 96 }, "ip" : "192.168.200.202" }, "transport" : "tcp", "type" : "flow", "dest" : { "port" : 9200, "stats" : { "net_bytes_total" : 18112, "net_packets_total" : 64 }, "ip" : "192.168.200.202" }, "tags" : [ "beats_input_raw_event" ], "start_time" : "2017-12-12T12:49:10.855Z", "@timestamp" : "2017-12-12T12:49:50.000Z", "flow_id" : "EAT/////AP//////CP8AAAHAqMjKwKjIyk6v8CM", "last_time" : "2017-12-12T12:49:10.855Z", "final" : false, "beat" : { "hostname" : "ubuntu", "name" : "ubuntu", "version" : "5.4.1" }, "@version" : "1", "host" : "ubuntu" } }, { "_index" : "packetbeat-2017.12.12", "_type" : "flow", "_id" : "AWBKxbt84UR9vnvGp98L", "_score" : 1.0, "_source" : { "transport" : "tcp", "source" : { "port" : 44884, "stats" : { "net_bytes_total" : 2863, "net_packets_total" : 2 }, "ip" : "192.168.200.202" }, "type" : "flow", "dest" : { "port" : 9200, "stats" : { "net_bytes_total" : 496, "net_packets_total" : 2 }, "ip" : "192.168.200.202" }, "tags" : [ "beats_input_raw_event" ], "start_time" : "2017-12-12T12:49:10.742Z", "@timestamp" : "2017-12-12T12:49:20.000Z", "last_time" : "2017-12-12T12:49:10.742Z", "flow_id" : "EAT/////AP//////CP8AAAHAqMjKwKjIylSv8CM", "final" : false, "beat" : { "hostname" : "ubuntu", "name" : "ubuntu", "version" : "5.4.1" }, "@version" : "1", "host" : "ubuntu" } }, { "_index" : "packetbeat-2017.12.12", "_type" : "flow", "_id" : "AWBKxbt94UR9vnvGp98N", "_score" : 1.0, "_source" : { "source" : { "stats" : { "net_bytes_total" : 3032, "net_packets_total" : 24 }, "port" : 44880, "ip" : "192.168.200.202" }, "transport" : "tcp", "dest" : { "port" : 9200, "stats" : { "net_bytes_total" : 3688, "net_packets_total" : 16 }, "ip" : "192.168.200.202" }, "type" : "flow", "tags" : [ "beats_input_raw_event" ], "start_time" : "2017-12-12T12:49:10.852Z", "@timestamp" : "2017-12-12T12:49:20.000Z", "last_time" : "2017-12-12T12:49:10.852Z", "flow_id" : "EAT/////AP//////CP8AAAHAqMjKwKjIylCv8CM", "final" : false, "beat" : { "hostname" : "ubuntu", "name" : "ubuntu", "version" : "5.4.1" }, "@version" : "1", "host" : "ubuntu" } }, { "_index" : "packetbeat-2017.12.12", "_type" : "flow", "_id" : "AWBKx0IB4UR9vnvGp99Y", "_score" : 1.0, "_source" : { "source" : { "stats" : { "net_bytes_total" : 62, "net_packets_total" : 1 }, "port" : 5044, "ip" : "192.168.0.104" }, "transport" : "tcp", "dest" : { "port" : 39330, "ip" : "192.168.200.202" }, "type" : "flow", "tags" : [ "beats_input_raw_event" ], "start_time" : "2017-12-12T12:50:31.758Z", "@timestamp" : "2017-12-12T12:51:00.000Z", "flow_id" : "EAT/////AP//////CP8AAAHAqABowKjIyrQTopk", "last_time" : "2017-12-12T12:50:31.758Z", "final" : false, "beat" : { "hostname" : "ubuntu", "name" : "ubuntu", "version" : "5.4.1" }, "@version" : "1", "host" : "ubuntu" } }, { "_index" : "packetbeat-2017.12.12", "_type" : "flow", "_id" : "AWBKx0IB4UR9vnvGp99a", "_score" : 1.0, "_source" : { "transport" : "tcp", "source" : { "port" : 39336, "stats" : { "net_bytes_total" : 380, "net_packets_total" : 5 }, "ip" : "192.168.200.202" }, "type" : "flow", "dest" : { "port" : 5044, "ip" : "192.168.0.104" }, "tags" : [ "beats_input_raw_event" ], "start_time" : "2017-12-12T12:50:44.555Z", "@timestamp" : "2017-12-12T12:51:00.000Z", "flow_id" : "EAT/////AP//////CP8AAAHAqABowKjIyrQTqJk", "last_time" : "2017-12-12T12:50:44.555Z", "final" : false, "beat" : { "hostname" : "ubuntu", "name" : "ubuntu", "version" : "5.4.1" }, "@version" : "1", "host" : "ubuntu" } }, { "_index" : "packetbeat-2017.12.12", "_type" : "flow", "_id" : "AWBKxqW94UR9vnvGp989", "_score" : 1.0, "_source" : { "source" : { "port" : 44880, "stats" : { "net_bytes_total" : 3032, "net_packets_total" : 24 }, "ip" : "192.168.200.202" }, "transport" : "tcp", "type" : "flow", "dest" : { "stats" : { "net_bytes_total" : 3688, "net_packets_total" : 16 }, "port" : 9200, "ip" : "192.168.200.202" }, "tags" : [ "beats_input_raw_event" ], "start_time" : "2017-12-12T12:50:11.260Z", "@timestamp" : "2017-12-12T12:50:20.001Z", "flow_id" : "EAT/////AP//////CP8AAAHAqMjKwKjIylCv8CM", "last_time" : "2017-12-12T12:50:11.260Z", "beat" : { "hostname" : "ubuntu", "name" : "ubuntu", "version" : "5.4.1" }, "final" : false, "@version" : "1", "host" : "ubuntu" } }, { "_index" : "packetbeat-2017.12.12", "_type" : "flow", "_id" : "AWBKx2kj4UR9vnvGp99f", "_score" : 1.0, "_source" : { "source" : { "port" : 49960, "stats" : { "net_bytes_total" : 480, "net_packets_total" : 5 }, "ip" : "192.168.200.202" }, "transport" : "tcp", "type" : "flow", "dest" : { "port" : 5044, "stats" : { "net_bytes_total" : 1548, "net_packets_total" : 3 }, "ip" : "192.168.200.202" }, "tags" : [ "beats_input_raw_event" ], "start_time" : "2017-12-12T12:50:23.727Z", "@timestamp" : "2017-12-12T12:51:10.000Z", "flow_id" : "EAT/////AP//////CP8AAAHAqMjKwKjIyijDtBM", "last_time" : "2017-12-12T12:50:23.727Z", "final" : true, "beat" : { "hostname" : "ubuntu", "name" : "ubuntu", "version" : "5.4.1" }, "@version" : "1", "host" : "ubuntu" } } ] } }Hi Cristian – it’s simple – try exploring tutorial https://crunchify.com/json-manipulation-in-java-examples/ for more details.
If you need quick toturial on this, send me complete JSON and requirement output format.
what library are you using ?
Hi Mulk – i’m using org.json maven library in this tutorial.
Are you getting any error? If you want to convert project to maven project then you could follow this tutorial: https://crunchify.com/how-to-convert-existing-java-project-to-maven-in-eclipse/
Hi Mulk – i’m using org.json maven library in this tutorial.
org.json
json
20151123
Are you getting any error? If you want to convert project to maven project then you could follow this tutorial: https://crunchify.com/how-to-convert-existing-java-project-to-maven-in-eclipse/
Hello Sir, I need some help from you. Actually i’m getting JSON data from a url and i want to show the data on my website. I
Successfully showing all JSON data except JSON Hierarchy data. I easily accessing Array data (“person”) and also in front
data(i.e “error”) but i can’t access hierarchy which is “updated”.
I have to access “updated.time”. I’m get very much frustrations in doing this. Can you help..?
import java.io.IOException; import java.net.URL; import org.apache.commons.io.IOUtils; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.JSONValue; import org.json.simple.parser.ParseException; public class ParseJson1 { public static void main(String[] args) { String url = "http://freemusicarchive.org/api/get/genres.json?api_key=60BLHNQCAOUFPIBZ&limit=2"; */ { "person": [ { "name": "John", "city": "Mumbai" }, { "name": "Rahul", "city": "Delhi" }, { "name": "Sanjana", "city": "Amritsar" }, { "name": "Anjali", "city": "Hyderabad" }, { "name": "Mukund", "city": "Bangalore" }, { "name": "Raunak", "city": "Patna" } ], "updated": { "time": "14:17:48", "date": "2016-04-10" }, "error": "2353", } /* try { String genreJson = IOUtils.toString(new URL(url)); JSONObject genreJsonObject = (JSONObject) JSONValue.parseWithException(genreJson); // get the error System.out.println(genreJsonObject.get("error")); //Get Array Values JSONArray genreArray = (JSONArray) genreJsonObject.get("person"); // get the first genre JSONObject firstGenre = (JSONObject) genreArray.get(0); System.out.println(firstGenre.get("name")); // get the Second JSONObject firstGenre = (JSONObject) genreArray.get(1); System.out.println(firstGenre.get("name")); // get the third JSONObject firstGenre = (JSONObject) genreArray.get(2); System.out.println(firstGenre.get("city")); } catch (IOException | ParseException e) { e.printStackTrace(); } } }Hi Subham –
Here is a program to get Updated.time from JSON Object.
package crunchify.com.tutorials; import java.io.FileReader; import java.io.IOException; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; /** * @author Crunchify.com * */ public class CrunchifyParseJSONObject { public static void main(String[] args) { JSONParser parser = new JSONParser(); try { Object obj = parser.parse(new FileReader("/Users/appshah/Documents/crunchify.txt")); JSONObject genreJsonObject = (JSONObject) obj; JSONObject updated = (JSONObject) genreJsonObject.get("updated"); String time = (String) updated.get("time"); System.out.println(time); } catch (IOException | ParseException e) { e.printStackTrace(); } } }Also, JSONObject I’m using is:
{ "person": [{ "name": "John", "city": "Mumbai" }, { "name": "Rahul", "city": "Delhi" }, { "name": "Sanjana", "city": "Amritsar" }, { "name": "Anjali", "city": "Hyderabad" }, { "name": "Mukund", "city": "Bangalore" }, { "name": "Raunak", "city": "Patna" }], "updated": { "time": "14:17:48", "date": "2016-04-10" } }when i am writing the below code in eclipse editor, It shows me syntax error in edirot and when i mouse hover it gives me 2 suggestiosn to fix :
1.Remove argument to match JSONObject
2.Change type of jsonData to map
public void getJSONData(String file) throws FileNotFoundException, JSONException { String jsonData = ""; BufferedReader br = null; try { String line; br = new BufferedReader(new FileReader(file)); 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); //return 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")); }Make sure you clean your project and json dependency is added correctly. I just tried it on my eclipse and it worked fine.
even i am facing the same problem did you fix it ?
Hi Nidhi – I’ve just updated above tutorial with org.json dependency. Can you try now?
at the following line “JSONObject obj = new JSONObject(jsonData);” I am getting error “Remove argument to match json” Or “change type of jsonData to map”
Hi Shraddha – i didn’t get it. Can you help share screenshot or any exception you are getting?
Hi Shraddha – I’ve added org.json dependency in above project. Please update project once you add .jar to your project or update pom.xml file.
I have followed the same procedure as u people told…
But getting the bellow error
can someone help
Hi Monika – can you share detailed stacktrace? try cleaning your project as error clearly shows it’s missing JSON jar file dependency.