<< Chapter < Page | Chapter >> Page > |
Revised: Thu Jun 02 19:28:45 CDT 2016
This page is included in the following Books:
This is a page from the book titled The json-simple Java Library . The book explains how to use the json-simple Java library to generate, transform, and query JSON text. This page explains how to read a JSON string containing nestedarray data from a file, decode it, and display its component parts.
I recommend that you open another copy of this module in a separate browser window and use the following links to easily find and view the Figuresand Listings while you are reading about them.
You learned how to encode JSON data containing nested arrays and how to write the encoded JSON string to an output file in the page titled Json0225: Encoding JSON Arrays . The program that I will discuss and explain in the next section will read thatfile from the disk, decode it, and display its component parts.
The program named Code (see Listing 7 ) reads and parses aninput file named junk.json , The file contains a JSON string with nested array data.
I will discuss and explain this program in fragments. The first fragment is shown in Listing 1 .
class Code{
public static void main(String[]args){
//Instantiate a JSONObject object, which is a subclass of the// Java HashMap class.
JSONObject jsonMap = null;try{
//Read json string from a file and parse it into a HashMap.jsonMap =
(JSONObject)(JSONValue.parse(new FileReader("junk.json")));}catch(IOException ex){
ex.printStackTrace();}//end catch
The code in Listing 1 shows the beginning of the class and the beginning of the main method. This code reads the JSON string from the input file named junk.json and parses the data into an object of type JSONObject .
There is nothing new in Listing 1 so the code shouldn't need further explanation. When the code in Listing 1 has finished executing, all of the information from the JSON string in the file is encapsulated in the object oftype JSONObject referred to as jsonMap .
Notification Switch
Would you like to follow the 'Object-oriented programming (oop) with java' conversation and receive update notifications?