Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Java Data Science Cookbook

You're reading from   Java Data Science Cookbook Explore the power of MLlib, DL4j, Weka, and more

Arrow left icon
Product type Paperback
Published in Mar 2017
Publisher Packt
ISBN-13 9781787122536
Length 372 pages
Edition 1st Edition
Languages
Tools
Arrow right icon
Author (1):
Arrow left icon
Rushdi Shams Rushdi Shams
Author Profile Icon Rushdi Shams
Rushdi Shams
Arrow right icon
View More author details
Toc

Table of Contents (10) Chapters Close

Preface 1. Obtaining and Cleaning Data FREE CHAPTER 2. Indexing and Searching Data 3. Analyzing Data Statistically 4. Learning from Data - Part 1 5. Learning from Data - Part 2 6. Retrieving Information from Text Data 7. Handling Big Data 8. Learn Deeply from Data 9. Visualizing Data

Reading JSON files using JSON.simple

In this recipe, we will see how we can read or parse a JSON file. As our sample input file, we will be using the JSON file we created in the previous recipe.

Getting ready

In order to perform this recipe, we will require the following:

  1. Use the previous recipe to create a JSON file with book, author, and reviewer comments information. This file will be used as an input for parsing/reading in this recipe.

How to do it ...

  1. As we will be reading or parsing a JSON file, first, we will be creating a JSON parser:
            JSONParser parser = new JSONParser(); 
    
  2. Then, in a try block, we will be retrieving the values in the fields book and author. However, to do that, we first use the parse() method of the parser to read the input JSON file. The parse() method returns the content of the file as an object. Therefore, we will need an Object variable to hold the content. Then, the object will be assigned to a JSON object for further processing. Notice the type cast of the Object variable during the assignment:
           try { 
     
             Object obj = parser.parse(new FileReader("c:test.json")); 
             JSONObject jsonObject = (JSONObject) obj; 
     
             String name = (String) jsonObject.get("book"); 
             System.out.println(name); 
     
             String author = (String) jsonObject.get("author"); 
             System.out.println(author); 
           }
    
  3. The next field to retrieve from the input JSON file is the review field, which is an array. We iterate over this field as follows:
     
           JSONArray reviews = (JSONArray) jsonObject.get("messages"); 
             Iterator<String> iterator = reviews.iterator(); 
             while (iterator.hasNext()) { 
                System.out.println(iterator.next()); 
           } 
    
  4. Finally, we create catch blocks to handle three types of exceptions that may occur during the parsing, and then close the method:
 
        } catch (FileNotFoundException e) { 
                 //Your exception handling here 
              } catch (IOException e) { 
                 //Your exception handling here 
              } catch (ParseException e) { 
                 //Your exception handling here 
              } 
        } 

The entire class, the method described in this recipe, and the driver method to run the method are as follows:

import java.io.FileNotFoundException; 
import java.io.FileReader; 
import java.io.IOException; 
import java.util.Iterator; 
import org.json.simple.JSONArray; 
import org.json.simple.JSONObject; 
import org.json.simple.parser.JSONParser; 
import org.json.simple.parser.ParseException; 
 
public class JsonReading { 
   public static void main(String[] args){ 
      JsonReading jsonReading = new JsonReading(); 
      jsonReading.readJson("C:/testJSON.json"); 
   } 
   public void readJson(String inFileName) { 
      JSONParser parser = new JSONParser(); 
      try { 
         Object obj = parser.parse(new FileReader(inFileName)); 
         JSONObject jsonObject = (JSONObject) obj; 
 
         String name = (String) jsonObject.get("book"); 
         System.out.println(name); 
 
         String author = (String) jsonObject.get("author"); 
         System.out.println(author); 
 
         JSONArray reviews = (JSONArray) jsonObject.get("messages"); 
         Iterator<String> iterator = reviews.iterator(); 
         while (iterator.hasNext()) { 
            System.out.println(iterator.next()); 
         } 
      } catch (FileNotFoundException e) { 
         //Your exception handling here 
      } catch (IOException e) { 
         //Your exception handling here 
      } catch (ParseException e) { 
         //Your exception handling here 
      } 
   } 
} 
 

On successful execution of the code, you will be able to see the contents of the input file on the standard output.

You have been reading a chapter from
Java Data Science Cookbook
Published in: Mar 2017
Publisher: Packt
ISBN-13: 9781787122536
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image