- JSON.simple — Environment Setup
- System Requirement
- Step 1: Verify Java Installation in Your Machine
- Step 2: Set JAVA Environment
- Step 3: Download JSON.simple Archive
- Step 4: Set JSON_JAVA Environment
- Step 5: Set CLASSPATH Variable
- JSON.simple – Read and Write JSON
- JSON.simple example – Read and write JSON
- Java JSON Tutorial Content:
- Write JSON to file:
- Read JSON to file:
- Project Structure:
- Was this post helpful?
- Share this
- Related Posts
- Author
- Related Posts
- Bash Get Everything After Character
- Bash Get Text Between Two Strings
- sed Remove Leading and Trailing Whitespace
- Bash Print Every nth Line from File
- sed Add Line to End of File
- Bash Sort CSV by Column
JSON.simple — Environment Setup
JSON.simple is a library for Java, so the very first requirement is to have JDK installed in your machine.
System Requirement
JDK | Memory | Disk Space | Operating System |
---|---|---|---|
1.5 or above. | No minimum requirement. | No minimum requirement. | No minimum requirement. |
Step 1: Verify Java Installation in Your Machine
First of all, open the console and execute a java command based on the operating system you are working on.
OS | Task | Command |
---|---|---|
Windows | Open Command Console | c:\> java -version |
Linux | Open Command Terminal | $ java -version |
Mac | Open Terminal | machine: < joseph$ java -version |
Let’s verify the output for all the operating systems −
Java(TM) SE Runtime Environment (build 1.8.0_101)
Java(TM) SE Runtime Environment (build 1.8.0_101)
Java(TM) SE Runtime Environment (build 1.8.0_101)
If you do not have Java installed on your system, then download the Java Software Development Kit (SDK) from the following link www.oracle.com. We are assuming Java 1.8.0_101 as the installed version for this tutorial.
Step 2: Set JAVA Environment
Set the JAVA_HOME environment variable to point to the base directory location where Java is installed on your machine. For example.
OS | Output |
---|---|
Windows | Set the environment variable JAVA_HOME to C:\Program Files\Java\jdk1.8.0_101 |
Linux | export JAVA_HOME = /usr/local/java-current |
Mac | export JAVA_HOME = /Library/Java/Home |
Append Java compiler location to the System Path.
OS | Output |
---|---|
Windows | Append the string C:\Program Files\Java\jdk1.8.0_101\bin at the end of the system variable, Path. |
Linux | export PATH = $PATH:$JAVA_HOME/bin/ |
Mac | not required |
Verify Java installation using the command java -version as explained above.
Step 3: Download JSON.simple Archive
Download the latest version of JSON.simple jar file from json-simple @ MVNRepository. At the time of writing this tutorial, we have downloaded json-simple-1.1.1.jar, and copied it into C:\>JSON folder.
OS | Archive name |
---|---|
Windows | json-simple-1.1.1.jar |
Linux | json-simple-1.1.1.jar |
Mac | json-simple-1.1.1.jar |
Step 4: Set JSON_JAVA Environment
Set the JSON_JAVA environment variable to point to the base directory location where JSON.simple jar is stored on your machine. Let’s assuming we’ve stored json-simple-1.1.1.jar in the JSON folder.
Set the environment variable JSON_JAVA to C:\JSON
export JSON_JAVA = /usr/local/JSON
export JSON_JAVA = /Library/JSON
Step 5: Set CLASSPATH Variable
Set the CLASSPATH environment variable to point to the JSON.simple jar location.
Set the environment variable CLASSPATH to %CLASSPATH%;%JSON_JAVA%\json-simple-1.1.1.jar;.;
export CLASSPATH = $CLASSPATH:$JSON_JAVA/json-simple-1.1.1.jar:.
export CLASSPATH = $CLASSPATH:$JSON_JAVA/json-simple-1.1.1.jar:.
JSON.simple – Read and Write JSON
JSON.simple is a lightweight JSON processing library that can be used to read and write JSON files and strings. The encoded/decoded JSON will be in full compliance with JSON specification (RFC4627).
JSON.simple library is pretty old and has not been updated since march, 2012. Google GSON library is a good option for reading and writing JSON.
In this Java JSON tutorial, we will first see a quick example of writing to a JSON file and then we will read JSON from the file.
- Full compliance with JSON specification (RFC4627).
- Supports encode, decode/parse and escape JSON.
- Easy to use by reusing Map and List interfaces.
- Supports streaming output of JSON text.
- High performance.
- No dependency on external libraries.
Update pom.xml with json-simple maven dependency.
com.googlecode.json-simple json-simple 1.1.1
To write JSON test into the file, we will be working with mainly two classes:
- JSONArray : To write data in json arrays. Use its add() method to add objects of type JSONObject .
- JSONObject : To write json objects. Use it’s put() method to populate fields.
After populating the above objects, use FileWriter instance to write the JSON file.
package com.howtodoinjava.demo.jsonsimple; import java.io.FileWriter; import java.io.IOException; import org.json.simple.JSONArray; import org.json.simple.JSONObject; public class WriteJSONExample < @SuppressWarnings("unchecked") public static void main( String[] args ) < //First Employee JSONObject employeeDetails = new JSONObject(); employeeDetails.put("firstName", "Lokesh"); employeeDetails.put("lastName", "Gupta"); employeeDetails.put("website", "howtodoinjava.com"); JSONObject employeeObject = new JSONObject(); employeeObject.put("employee", employeeDetails); //Second Employee JSONObject employeeDetails2 = new JSONObject(); employeeDetails2.put("firstName", "Brian"); employeeDetails2.put("lastName", "Schultz"); employeeDetails2.put("website", "example.com"); JSONObject employeeObject2 = new JSONObject(); employeeObject2.put("employee", employeeDetails2); //Add employees to list JSONArray employeeList = new JSONArray(); employeeList.add(employeeObject); employeeList.add(employeeObject2); //Write JSON file try (FileWriter file = new FileWriter("employees.json")) < //We can write any JSONArray or JSONObject instance to the file file.write(employeeList.toJSONString()); file.flush(); >catch (IOException e) < e.printStackTrace(); >> >
To read JSON from file, we will use the JSON file we created in the previous example.
- First of all, we will create JSONParser instance to parse JSON file.
- Use FileReader to read JSON file and pass it to parser.
- Start reading the JSON objects one by one, based on their type i.e. JSONArray and JSONObject .
package com.howtodoinjava.demo.jsonsimple; 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; public class ReadJSONExample < @SuppressWarnings("unchecked") public static void main(String[] args) < //JSON parser object to parse read file JSONParser jsonParser = new JSONParser(); try (FileReader reader = new FileReader("employees.json")) < //Read JSON file Object obj = jsonParser.parse(reader); JSONArray employeeList = (JSONArray) obj; System.out.println(employeeList); //Iterate over employee array employeeList.forEach( emp ->parseEmployeeObject( (JSONObject) emp ) ); > catch (FileNotFoundException e) < e.printStackTrace(); >catch (IOException e) < e.printStackTrace(); >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); >>
[ >, > ] Lokesh Gupta howtodoinjava.com Brian Schultz example.com
JSON.simple example – Read and write JSON
In this post,we will see how can we read and write JSON using json.simple.
Java JSON Tutorial Content:
JSON.simple, is a simple Java library for JSON processing, read and write JSON data and full compliance with JSON specification (RFC4627).
In this post,we will read and write JSON using JSON.simple.
Download JSON.simple jar from here.
Create a java project named “JSONSimpleExample”
Create a folder jars and paste downloaded jar json-simple-1.1.1.jar.
right click on project->Property->java build path->Add jars and then go to src->jars->json-simple-1.1.1.jar.
Click on ok.
Then you will see json-simple-1.1 jar added to your libraries and then click on ok
Write JSON to file:
Create a new class named “JSONSimpleWritingToFileExample.java” in src->org.arpit.java2blog
Run above program and you will get following output:
Read JSON to file:
Here we will read above created JSON file.
Create a new class named “JSONSimpleReadingFromFileExample.java” in src->org.arpit.java2blog
Run above program and you will get following output:
Project Structure:
Was this post helpful?
Share this
Related Posts
Author
Related Posts
Bash Get Everything After Character
Table of ContentsUsing Parameter ExpansionUsing cut CommandUsing awk CommandUsing sed CommandUsing grep CommandUsing expr CommandUsing the IFS Variable and read Command Using Parameter Expansion Use parameter expansion to get everything after character in Bash. [crayon-64b8e1fec606a005965195/] [crayon-64b8e1fec6070263712352/] First, we set the string variable with a string type value; then, we initialised the delimiter variable with a […]
Bash Get Text Between Two Strings
Table of ContentsUsing grep Command with -oP optionUsing sed CommandUsing awk CommandUsing Bash Parameter Expansion Using grep Command with -oP option Use the grep with -oP option to get text between two strings in bash. [crayon-64b8e1fec6427055595379/] [crayon-64b8e1fec642b297410101/] In this example, first, the string variable contained the string «Start text[Extract this]End text» from this, we want […]
sed Remove Leading and Trailing Whitespace
Table of ContentsUsing sed Command with SubstitutionsUsing sed Command with POSIX Substitutions Using sed Command with Substitutions Use the sed command with multiple substitutions to remove leading and trailing whitespaces from a single-line string in Bash. [crayon-64b8e1fec6566002783248/] [crayon-64b8e1fec6568840248063/] First, we created a variable named str and set its value to a string value which contained […]
Bash Print Every nth Line from File
Table of ContentsUsing awk CommandUsing sed CommandUsing perl Command Using awk Command Use the awk command to print every nth line from file in Bash. [crayon-64b8e1fec6737070453038/] [crayon-64b8e1fec673b406915349/] [crayon-64b8e1fec673c755591694/] [crayon-64b8e1fec673d727642480/] In this example, the awk command gets every 4th line from the file test.txt. Here, the file variable contains the file name from where you want […]
sed Add Line to End of File
Table of ContentsUsing sed with a command:Using sed with s command:Using sed with r Command Using sed with a command: Use sed with the a command to add a line to the file’s end in Bash. [crayon-64b8e1fec69bb391509981/] [crayon-64b8e1fec69bf555778823/] In this example, the sed command is used with the a option to add a line This […]
Bash Sort CSV by Column
Table of ContentsBash Sort CSV by ColumnUsing sort CommandUsing csvsort UtilityBash Sort CSV by Multiple Columns Bash Sort CSV by Column Using sort Command Use bash’s sort command to sort the CSV file by column. [crayon-64b8e1fec6afa172474926/] [crayon-64b8e1fec6afd933027921/] [crayon-64b8e1fec6afe492824076/] In this example, the sort command is used to sort the myFile.csv file by column. Here, the […]