Write and Parse JSON in JAVA
JSON is a simple text data format as well as it is not dependent on any language. In many programming languages, JSON parsers and generator libraries are readily available. Let's discuss how to write and read JSON in JAVA.
Consider the following sample JSON Document :
JSON mainly creates two structures: A collection of name-value pairs and a List of values. In the above JSON Document name and size are key and value pairs, updateby and section are the list of values, Value of updateby and Metadata cover as a nested form of key-value or list of values.
Setup
There are many jars readily available in JAVA. Here will use Org-JSON to write the above object in JAVA. For this, we need to add the following dependency in our maven project or download an imported jar in the Java project. Click here to get the updated jar.
Write JSON in JAVA
STEP 1: To write JSON, First you need to import a JSON Jar and create a JSON Object.
STEP 2: For Key value pairs, we can put the key and respective value in the created object.
STEP 3: To Create a JSON Array, we need to use JSONArray Class.
To insert JSON Array in JSON Object, we need to use the same put() method.
STEP 4: Similarly we can add JSON Object in JSON Object or we can create a JSON Object array.
Let’s see a complete code of write JSON data :
Parse JSON in JAVA
STEP 1: To parse JSON, First you need to import a JSON Jar and create a JSON Object with JSON String argument.
STEP 2: To read all the keys, we need to take an iterator.
STEP 3: Initialize any control flow statement to extract data from Object.
To identify data type we can use instanceof keyword, for example
Let’s see a complete code of parse JSON data :
Download
JSON In Java Jar : Click here
JSON.simple Jar : Click here
Source Code : Click here
Credits
JSON In Java Jar - Java JSON encoders/decoders package
json.org - Introducing JSON Standard