JAVA JSON PARSING
IT PROF 17
THIS LESSON COVERS THE FOLLOWING
TOPICS:
1. How to setup programming environment using Netbeans with Java
for JSON?
2. How to encode and decode JSON objects using Java programming
language.
3. How to read and write JSON file?
4. How to parse JSON URL using Java?
SKIP THIS SLIDE IF YOU HAVE INSTALLED NETBEANS AND JDK IN YOUR COMPUTER
ALREADY!
HOW TO INSTALL NETBEANS ON
WINDOWS?
1. Install JDK – Go to this link for instruction :
https://www3.ntu.edu.sg/home/ehchua/programming/howto/JDK_HowTo.h
tml
2. Download "NetBeans IDE" installer from
http://netbeans.org/downloads/index.html. There are many
"bundles" available. For beginners, choose the 1st entry "Java SE"
(e.g., "netbeans-8.2-javase-windows.exe" 95MB).
3. NOTE:
Run the
If youInstaller
can’t download the installers due to No/Slow Internet Connection. You
can ask for a copy from your instructor.
ADDING .JAR FILE TO THE PROJECT
• Right-click “libraries” in the project
list, then click add JAR/Folder.
• Locate the “json-simple.jar” file,
then click open.
WHAT IS JSONOBJECT?
A JSONObject is an unordered collection of key and value pairs, resembling Java's native Map implementations.
• Keys are unique Strings that cannot be null
• Values can be anything from a Boolean, Number, String, JSONArray or even a JSONObject.NULL object
• A JSONObject can be represented by a String enclosed within curly braces with keys and values separated by a colon, and
pairs separated by a comma
• It has several constructors with which to construct a JSONObject
It also supports the following main methods:
1. get(String key) – gets the object associated with the supplied key, throws JSONException if the key is not found
2. opt(String key)- gets the object associated with the supplied key, null otherwise
3. put(String key, Object value) – inserts or replaces a key-value pair in current JSONObject.
The put() method is an overloaded method which accepts a key of type String and multiple types for the value.
CREATING A PROJECT IN NETBEANS:
1. Open the Netbeans Application.
2. From "File" menu ⇒ Choose "New Project...".
3. The "Choose Project" dialog pops up ⇒ Under
"Categories", choose "Java" ⇒ Under "Projects",
choose "Java Application" ⇒ "Next".
4. The "Name and Location" dialog pops up ⇒ Under
"Project Name", enter “YourCompleteNameProject"
⇒ In "Project Location", select a suitable directory to
save your works ⇒ Uncheck "Use Dedicated Folder
for Storing Libraries" ⇒ Uncheck "Create Main
class" ⇒ Finish. CONTINUE ON THE NEXT SLIDE…..
JSONOBJECT EXAMPLE:
1. Create a java file
named it
“JSONEncodeDemo”
and copy the codes on
the image at the right
side.
2. Run the project and see
the output.
Example to encode a JSON object using Java
JSONObject
WHAT IS JSONARRAY?
A JSONArray is an ordered collection of values, resembling Java's native Vector implementation.
• Values can be anything from a Number, String, Boolean, JSONArray, JSONObject or even
a JSONObject.NULL object
• It's represented by a String wrapped within Square Brackets and consists of a collection of values separated by
commas
• Like JSONObject, it has a constructor that accepts a source String and parses it to construct a JSONArray
The following are the primary methods of the JSONArray class:
1. get(int index) – returns the value at the specified index(between 0 and total length – 1), otherwise throws a JSONException
2. opt(int index) – returns the value associated with an index (between 0 and total length – 1). If there's no value at that index, then a null is returned
3. put(Object value) – append an object value to this JSONArray. This method is overloaded and supports a wide range of data types
JSONARRAY EXAMPLE:
1. Create another java file named it
“JSONEncodeDemo2” and copy the
codes on the image at the right side.
2. Run the project and see the output.
Example to encode a JSON array using Java
JSONArray and put into a JSONObject
import java.io.FileWriter;
import java.io.IOException;
import org.json.simple.JSONArray;
WRITING JSON INTO THE FILE
import org.json.simple.JSONObject;
public class WriteJSONExample
{
public static void main( String[] args )
{
//First Employee
• Create another java file and
JSONObject employeeDetails = new JSONObject();
employeeDetails.put("firstName", "Lokesh");
employeeDetails.put("lastName", "Gupta");
employeeDetails.put("website", "howtodoinjava.com");
named it JSONObject employeeObject = new JSONObject();
employeeObject.put("employee", employeeDetails);
“WriteJSONExample”. //Second Employee
JSONObject employeeDetails2 = new JSONObject();
employeeDetails2.put("firstName", "Brian");
employeeDetails2.put("lastName", "Schultz");
• Copy the codes at the right employeeDetails2.put("website", "example.com");
JSONObject employeeObject2 = new JSONObject();
employeeObject2.put("employee", employeeDetails2);
side. //Add employees to list
JSONArray employeeList = new JSONArray();
employeeList.add(employeeObject);
• Run this file and see the output.
employeeList.add(employeeObject2);
//Write JSON file
try (FileWriter file = new FileWriter("./src/employees.json")) {
//We can write any JSONArray or JSONObject instance to the file
file.write(employeeList.toJSONString());
file.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
}
SEE DEMONSTRATION ON THE NEXT
SLIDE…
READING A JSON FILE import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
• Create another java file and
public class ReadJSONExample
{
@SuppressWarnings("unchecked")
public static void main(String[] args)
{
named it
//JSON parser object to parse read file
JSONParser jsonParser = new JSONParser();
try (FileReader reader = new FileReader(“./src/employees.json"))
“ReadJSONExample”.
{
//Read JSON file
Object obj = jsonParser.parse(reader);
JSONArray employeeList = (JSONArray) obj;
• Copy the codes at the right
System.out.println(employeeList);
//Iterate over employee array
employeeList.forEach( emp -> parseEmployeeObject( (JSONObject) emp ) );
side. } catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
• Run this file and see the output.
} catch (ParseException e) {
e.printStackTrace();
}
}
private static void parseEmployeeObject(JSONObject employee)
{
//Get employee object within list
JSONObject employeeObject = (JSONObject) employee.get("employee");
//Get employee first name
String firstName = (String) employeeObject.get("firstName");
System.out.println(firstName);
//Get employee last name
String lastName = (String) employeeObject.get("lastName");
System.out.println(lastName);
//Get employee website name
String website = (String) employeeObject.get("website");
System.out.println(website);
}
}
PARSING A JSON URL import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.nio.charset.Charset;
• Create another java file and
import org.json.JSONArray;
import org.json.JSONObject;
public class JSONSimple {
named it public static void main(String args[]) {
“ParseJSONURLExample”.
String url = "https://sparry-song.000webhostapp.com/students.php";
try {
InputStream is = new URL(url).openStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
• Copy the codes at the right StringBuilder sb = new StringBuilder();
int cp;
while ((cp = rd.read()) != -1) {
side. }
sb.append((char) cp);
JSONArray array = new JSONArray(sb.toString());
• Run this file and see the output.
//JSONObject json = new JSONObject(sb.toString());
// System.out.println(json.get("student_id"));
for (int i = 0; i < array.length(); i++) {
JSONObject object = (JSONObject) array.get(i);
System.out.println("Student Id: "+object.get("student_id"));
System.out.println("Student Name: "+object.get("student_name"));
System.out.println("Course Name: "+object.get("course_name"));
System.out.println("Year Level: "+object.get("year_level"));
System.out.println("Date Enrolled: "+object.get("enrolled_date"));
System.out.println();
}
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
LESSON 4 – ACTIVITY LINK:
https://forms.gle/HyeAA5Ckgb6ToT7L6