<< Chapter < Page | Chapter >> Page > |
Revised: Thu Jun 02 19:27:08 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 encode JSON array data using the JSONArray class. It also shows how to write an encoded JSON string to an output text file for transport to a different programmingenvironment.
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.
As you learned in the page titled Json0210: Structure of the json-simple Java Library , the JSONArray class extends the standard Java ArrayList class. Once you have an object of the JSONArray class, you have access to all of the methods defined in and inherited into the JSONArray class.
The sample program that follows will use the JSONArray class to construct a JSON string containing nested arrays and will then write thestring to an output file suitable for transport to a different programming environment.
A later page in this book will read the JSON string from the file and decode it into its component parts.
The program named Code (see Listing 7 ) creates a JSON string and writes it to an output file. The json string contains an array, which in turn contains two nested arrays.
I will discuss and explain the program in fragments. The first fragment is shown in Listing 1 .
import org.json.simple.JSONObject;
import org.json.simple.JSONArray;import java.io.PrintWriter;
import java.io.File;import java.io.IOException;
class Code{public static void main(String[] args){//Create a json object. which is a subclass
// of the Java HashMap class.JSONObject hashMapA = new JSONObject();//Populate the json object with a key/value
// pair.hashMapA.put("name","Tom");
Notification Switch
Would you like to follow the 'Object-oriented programming (oop) with java' conversation and receive update notifications?