Reading and Writing JSON with Java and JQuery

Reading and Writing JSON with Java and JQuery

October 9, 2016


Recently, I worked on a project that dealt with a great deal of JSON reading, writing, and manipulation. As it was my first time working JSON, I ran into quite a few road-bumps and mishaps. This post is going to share what I learned from these issues and hopefully help you from running into them yourself.

Note: While the Java examples can be ran as a Java Application, in order for the JQuery/AJAX to work, you will need to run the readJSON.html on a server. I built a Dynamic Web Project in Eclipse and ran the project on Tomcat.

JARS Needed: JSON.simple

Or Maven:

<dependency>
	<groupId>com.googlecode.json-simple</groupId>
	<artifactId>json-simple</artifactId>
	<version>1.1</version>
</dependency>

At a Glance (click for quicker access):

1) Writing JSON data to an external file with Java
2) Reading JSON data from an external file with Java
3) Reading JSON data and using it from an external file with JQuery and AJAX

Before Starting:

a) Make sure that your JSON file has nothing in it except for: []
b) Create a String variable with a path to your JSON file. Since I placed my JSON file in my project, I can access it locally so I do not need to add a path to it. I would recommend you do the same to keep your process simple and access the file easier.
c) Create String variables of the data you want inserted into your JSONArray.
d) Both the Writing and Reading Java code will be within a try and catch. The catch will have IOException and ParseExceptions.

b) String jsonFile = "learning.json";

c) String firstName = "Weston";
c) String talentsOne = "music";
c) String talentTwo = "coding";
c) String talentThree = "design";

d) try{} catch(IOException | ParseException excep){}

 

Writing JSON Data to an External File with Java.

a) Create a FileReader Object – You can’t work with a file if the application doesn’t know where it is. This object finds the JSON file according to the path and name that we put in as a parameter and allows us to work with it. Basically, it gives you access to the file.

b) Create a JSONParser Object – We need something that is able to look at the JSON file, read, and understand what the data means within it.

c) Set the parsed JSON file to an Object – Now we can parse the FileReader object and set it to an Object.

d) Cast and Set Object to JSONArray – Create a new JSONArray and then set it to the Object created in step c but with a cast of JSONArray. We now have a JSONObject that we can manipulate data to and from.

a) FileReader fr = new FileReader(jsonFile);
b) JSONParser jpar = new JSONParser();
c) Object ob = jpar.parse(fr);
d) JSONArray learningJSONArray = (JSONArray)ob;

Now we can start creating JSONObjects to add to our JSONArray.

a) Create a new JSONObject
b) Add data to the JSONObject – To add data to the JSONObject, you will utilize its ‘put’ method.
This method takes two parameters:

1) The name of the data field written inside quotation marks.
2) The actual data.

a) JSONObject userObjectJO = new JSONObject();
b) userObjectJO.put("firstName", firstName);

Adding a JSONArray to our JSONArray

a) Create a new JSONArray
b) Add data to the JSONArray – to add data to the JSONArray we will use the ‘add’ method of the JSON array. The method only takes one parameter, the data.

a) JSONArray talents = new JSONArray();
b) talents.add(talentsOne);
b) talents.add(talentTwo);
b) talents.add(talentThree);

This simply creates a JSONArray holding the inputted values. Now we’ll add the talents JSONArray to our JSONObject.

a) Using the JSONObject’s ‘put’ method, we will give it a data field name, and then our talentsJSONArray.

a) userObjectJO.put("talents", talents);

Adding the JSONObject to the main JSONArray

a) Now, for our last JSON step, we will add our JSONObject userObjectJO to the main JSONArray learningJSONArray.

a). learningJSONArray.add(userObjectJO);

Writing the new JSON Data to the JSON file

Now that we have all of our data created and added to the main JSONArray, we just have to write the new data to the external JSON file using Java’s FileWriter.

a) Here we create a new FileWriter with our JSON file path/name as a parameter.
b) Now we’ll actually write the JSONArray we created, learningJSONArray, to our file. However, to make sure we can interpret the JSON file in the future, we have to use the ‘toJSONString’ method.
c) Now, just close the FileWriter.

a) FileWriter fw = new FileWriter(jsonFile);
b) fw.write(learningJSONArray.toJSONString());
c) fw.close();

Here’s the whole code:

import java.io.FileReader;
import java.io.FileWriter;
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;

public class Search
{
	public static void main(String args[])
	{
		        String jsonFile = "learning.json";
				
			String firstName = "Weston";
			String talentsOne = "music";
			String talentTwo = "coding";
			String talentThree = "design";
			
			try
			{
				
				/*a)*/ FileReader fr = new FileReader(jsonFile);
				/*b)*/ JSONParser jpar = new JSONParser();
				/*c)*/ Object ob = jpar.parse(fr);
				/*d)*/ JSONArray learningJSONArray = (JSONArray)ob;
				
				JSONObject userObjectJO = new JSONObject();
				userObjectJO.put("firstName", firstName);
				
				JSONArray talents = new JSONArray();
				talents.add(talentsOne);
				talents.add(talentTwo);
				talents.add(talentThree);
							
				userObjectJO.put("talents", talents);
				
				learningJSONArray.add(userObjectJO);		
				
				FileWriter fw = new FileWriter(jsonFile);
				fw.write(learningJSONArray.toJSONString());
				fw.close();
				
			} catch (IOException | ParseException e)
			{
				System.out.println("Could not write data to learning.json file.");
				e.printStackTrace();
			}
	}
}

 

Reading JSON Data from an External JSON File With Java

The first part of the code is exactly the same as our Writing JSON code from above. We get access to the JSON file, create a JSONParser, parse the file, set it to an Object, and then cast that Object to a new JSONArray.

JSONParser jpar = new JSONParser();
FileReader fr = new FileReader(jsonFile);
Object ob = jpar.parse(fr);
JSONArray learningJSONArray = (JSONArray)ob;

Looping Through the JSONArray Data

Now that we have access to our JSONArray, we will loop through the array to grab and set values.

a) Get the JSONArray length to know how many times we need to loop.

int learningJSONArraySize = learningJSONArray.size();

b) Create a for loop to loop through the learningJSONArray

for(int i = 0; i < learningJSONArraySize; i++){}

 

Accessing the JSON Data

Let’s take a second to understand how our JSON file is structured. We have the main JSONArray, and within it, a JSONObject. This JSONObject is in the first index of the JSONArray, so to gain access to it, we’ll have to set a new JSONObject to the JSONObject at that JSONArray’s index of 0.

[
     {
     "firstName": "Weston",
     "talents": [
                   "music",
                   "coding",
                   "design"
                 ]
      }
 ]

The following code will reside within the previously created for loop above.

a) Create a new JSONObject – To gain access to the current JSONObject, we will use the JSONArray’s method ‘get’. For the index number, we will get the integer i created from the for loop and place it in the get method as a parameter. To make the new JSONObject set to a JSONObject, we will then cast the JSONArray’s index value to a JSONObject.

a) JSONObject currentUser = (JSONObject)learningJSONArray.get(i);

b) Set JSONObject values to String Variables – Now that we have a JSONObject, we can access its data.

i) To access the first piece, we can use the JSONObject’s ‘get’ method with the data field name as a parameter in quotation marks. Once we have this value, we cast it with String and then set it to a string variable.

i) String userFirstName = (String)currentUser.get("firstName");

ii) To access the array, we will grab the JSONArray using the same method above, ‘get’, but cast it to JSONArray and set it to a new JSONArray. Now we simply grab each piece of data by using the JSONArray’s ‘get’ method, inputting an index value as a parameter, and then set it to a String variable.

ii) JSONArray userTalentsArray = (JSONArray) currentUser.get("talents");
ii) String userTalentOne = (String)userTalentsArray.get(0);
ii) String userTalentTwo = (String)userTalentsArray.get(1);
ii) String userTalentThree = (String)userTalentsArray.get(2);

Here’s the whole code:

import java.io.FileReader;
import java.io.FileWriter;
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;

public class Search
{
	public static void main(String args[])
	{
            String jsonFile = "learning.json";
		try
		{
			JSONParser jpar = new JSONParser();
			FileReader fr = new FileReader(jsonFile);
			Object ob = jpar.parse(fr);
			JSONArray learningJSONArray = (JSONArray)ob;
			
			int learningJSONArraySize = learningJSONArray.size();
			
			for(int i = 0; i < learningJSONArraySize; i++){
				JSONObject currentUser = (JSONObject)learningJSONArray.get(i);
				String userFirstName = (String)currentUser.get("firstName");
				JSONArray userTalentsArray = (JSONArray) currentUser.get("talents");	
				String userTalentOne = (String)userTalentsArray.get(0);
				String userTalentTwo = (String)userTalentsArray.get(1);
				String userTalentThree = (String)userTalentsArray.get(2);
				System.out.println("First Name: "+userFirstName+"\n"
						+ "First Talent: "+userTalentOne+"\n"
						+ "Second Talent: "+userTalentTwo+"\n"
						+ "Third Talent: "+userTalentThree);
			}
			
		} catch (IOException | ParseException e)
		{
			System.out.println("Could not write data to learning.json file.");
			e.printStackTrace();
		}
	}
}

 

GETting the JSON Data with AJAX

To read and use the external JSON file data, we will use two tools. An AJAX get method and a JQuery each function.

Getting Access to JSON Data Using AJAX

AJAX is the reason the readJSON.html file must be opened on a server. It is what allows us to reach into the server to retrieve the learning.json file.

The first two pieces to the ajax method are pretty self-explanatory:

type – What we are doing with external data, in this case ‘GET’ting.
dataType – The type of data we want to retrieve. For this example it is json, however ajax has other types that can be retrieved such as html, jsonp, or text.

url – Again, depending on whether you have the file local on your application or somewhere else on your computer will depend on what is put in for this parameter. In my case, since I have the learning.json file saved in my applicaiton, I can simply use the file name.

success – Now that you know the where and how of your json data, it is time to do something with that data. This is where the success function comes in. Passed through the function is the learning.json data, which we can in turn use in any which way we want.

$.ajax({
 type: "GET",
 dataType: "json",
 url: "learning.json",
 success: function(jsonData){
 }
 });

Using JQuery to Manipulate JSON Data

Now that we have access to the data from the ajax call method, we can start to do something with that data. This is where the JQuery ‘each’ function comes in. Basically, the function has a starting value that it will look at(in this case the entire learning.json file data), and then traverses across each index and value. Each index and value then can be used as a JavaScript variable in methods and etc.

Before Starting:

1) Make sure you have the JQuery script on your page.
2) Create a div with an id of jsonDataDiv – this will hold the JSON data

a) We start with the learning.json data held in the jsonData variable as the first parameter to the ‘each’ function. For the second parameter, we place in a function with the two parameters index and value. The name of these parameters can be whatever you like, I just use these names so I know what I’m working with. The ‘index’ represents the index number of the JSON Object held in the main JSONArray. The ‘value’ parameter represents that value of the object at that particular ‘index’.

i)In short terms, jsonData represent the learning.json JSONArray, index represents the JSONObject’s index place in the JSONArray, and value represents the JSONObject’s data value.

b) Here we select with JQuery the div that we want the JSON data to be placed, and the fire the JQuery ‘append’ method. To output html element with the JSON data, we have to put any html markup in quotes. The JavaScript variables will not be surrounded with quotes, however.

c) We now write a beggining and ending html paragraph element surrounded with quotes. Inside the quotes will be the JSON data. Since value represents the first JSONObject from the learning.json file, we can grab the data field by writing value and in square brackets [] the data field that we want to retrieve.

d) Now we want to grab the ‘talents’ data field, so we will select it with the same method used previously like so: value[“talents”]. This part is where it gets interesting. The data inside the ‘talents’ JSONArray do not have field names to grab values from, so instead we can use a nested JQuery ‘each’ function to grab its values. The value[‘talents’] then becomes the starting piece of data and then the each function iterates through each index’s value. NOTE: Notice that the two parameters inside this function do not have the same name as the previous ‘each’ function. You have to think of these as JavaScript variables. One variable cannot have the same as another. If you accidentally place in ‘value’ instead of ‘valu’, then the each function would simply just iterate through all of the value data.

e) Here we just start another JQuery ‘append’ method with the #jsonDataDiv selected.

f) Again, we create paragraph html elements and surround them with quotes. Inside of these elements we simply place the valu parameter which will represent the value of the current index in the each loop. For example, on the first loop, at index ‘0’, valu would be ‘music’.

"talents": [
 "music", //inde 0
 "coding", //inde 1
 "design" //inde 2
 ]
a) $.each(jsonData, function(index, value){
b) $("#jsonDataDiv").append(
c) "

"<p>"+value["firstName"]+"</p>"
);
d) $.each(value["talents"], function(inde, valu){
e) $("#jsonDataDiv").append(
f) "<p>"+valu+"</p>" 

); }); });

 

Retrieving JSON Data on Page Load Instantly

Sometimes, if we have a page that pulls in data dynamically, we may want that page to load and populate that data instantly once the page pulls up.

a) To do this we will wrap the above AJAX and JQuery functions with a new function called ‘viewJSONData’. This function can be named whatever you like.
b) We then set the ‘window’ to run the function when it is ‘(on)load’ing.

a) function viewJSONData (){

AJAX FUNCTION
JQUERY FUNCTIONS

}
b) window.onload = viewJSONData;

Putting It All Together

Here’s the whole code for Getting JSON data with JQuery and AJAX

<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script>
function viewJSONData(){
		
			$.ajax({
				type: "GET", 
				dataType: "json",
				url: "learning.json",
				success: function(jsonData){
					$.each(jsonData, function(index, value){
						$("#jsonDataDiv").append(
                                                  "<p>"+value["firstName"]+"</p>"		
                                                );
						$.each(value["talents"], function(inde, valu){	
							$("#jsonDataDiv").append(
								"<p>"+valu+"</p>"		
							);
						});
					});
				}
			});
		}
		window.onload = viewJSONData;
</script>
<div id="jsonDataDiv"></div>