Let’s fun begin with Manipulating JSON Objects and Array with Java. If you want to learn fundamental about JSON, you can read more here.
We will use this input data for this post example: https://crunchify.com/wp-content/uploads/code/jsonArray.txt
Example 1: Complete example
package com.crunchify;
/**
* @author Crunchify.com
*/
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.Charset;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class CrunchifyJSON {
public static void main(String[] args) {
String jsonString = callURL("https://crunchify.com/wp-content/uploads/code/jsonArray.txt");
System.out.println("\n\njsonString: " + jsonString);
// Replace this try catch block for all below subsequent examples
try {
JSONArray jsonArray = new JSONArray(jsonString);
System.out.println("\n\njsonArray: " + jsonArray);
} catch (JSONException e) {
e.printStackTrace();
}
}
public static String callURL(String myURL) {
System.out.println("Requested URL:" + myURL);
StringBuilder sb = new StringBuilder();
URLConnection urlConn = null;
InputStreamReader in = null;
try {
URL url = new URL(myURL);
urlConn = url.openConnection();
if (urlConn != null)
urlConn.setReadTimeout(60 * 1000);
if (urlConn != null && urlConn.getInputStream() != null) {
in = new InputStreamReader(urlConn.getInputStream(),
Charset.defaultCharset());
BufferedReader bufferedReader = new BufferedReader(in);
if (bufferedReader != null) {
int cp;
while ((cp = bufferedReader.read()) != -1) {
sb.append((char) cp);
}
bufferedReader.close();
}
}
in.close();
} catch (Exception e) {
throw new RuntimeException("Exception while calling URL:"+ myURL, e);
}
return sb.toString();
}
}
Output:
Requested URL:https://crunchify.com/wp-content/uploads/code/jsonArray.txt
jsonString: [
{
color: "red",
value: "#f00"
},
{
color: "green",
value: "#0f0"
},
{
color: "blue",
value: "#00f"
},
{
color: "cyan",
value: "#0ff"
},
{
color: "magenta",
value: "#f0f"
},
{
color: "yellow",
value: "#ff0"
},
{
color: "black",
value: "#000"
}
]
jsonArray: [{"color":"red","value":"#f00"},{"color":"green","value":"#0f0"},{"color":"blue","value":"#00f"},{"color":"cyan","value":"#0ff"},{"color":"magenta","value":"#f0f"},{"color":"yellow","value":"#ff0"},{"color":"black","value":"#000"}]
Another must read: How to Merge/Concat Multiple JSONObjects in Java? Best way to Combine two JSONObjects
Example 2: Iterate through JSONArray and display each JSONObjects
try {
JSONArray jsonArray = new JSONArray(jsonString);
int count = jsonArray.length(); // get totalCount of all jsonObjects
for(int i=0 ; i< count; i++){ // iterate through jsonArray
JSONObject jsonObject = jsonArray.getJSONObject(i); // get jsonObject @ i position
System.out.println("jsonObject " + i + ": " + jsonObject);
}
} catch (JSONException e) {
e.printStackTrace();
}
Output:
jsonObject 0: {"color":"red","value":"#f00"}
jsonObject 1: {"color":"green","value":"#0f0"}
jsonObject 2: {"color":"blue","value":"#00f"}
jsonObject 3: {"color":"cyan","value":"#0ff"}
jsonObject 4: {"color":"magenta","value":"#f0f"}
jsonObject 5: {"color":"yellow","value":"#ff0"}
jsonObject 6: {"color":"black","value":"#000"}
Example 3: How to add JSONObject to JSONArray?
try {
JSONArray jsonArray = new JSONArray(jsonString);
JSONObject jsonObj= new JSONObject(); // these 4 files add jsonObject to jsonArray
jsonObj.put("color", "CrunchifyColor1");
jsonObj.put("value", "#111");
jsonArray.put(jsonObj);
int count = jsonArray.length(); // get totalCount of all jsonObjects
for(int i=0 ; i< count; i++){ // iterate through jsonArray
JSONObject jsonObject = jsonArray.getJSONObject(i); // get jsonObject @ i position
System.out.println("jsonObject " + i + ": " + jsonObject);
}
} catch (JSONException e) {
e.printStackTrace();
}
Output:
jsonObject 0: {"color":"red","value":"#f00"}
jsonObject 1: {"color":"green","value":"#0f0"}
jsonObject 2: {"color":"blue","value":"#00f"}
jsonObject 3: {"color":"cyan","value":"#0ff"}
jsonObject 4: {"color":"magenta","value":"#f0f"}
jsonObject 5: {"color":"yellow","value":"#ff0"}
jsonObject 6: {"color":"black","value":"#000"}
jsonObject 7: {"color":"CrunchifyColor1","value":"#111"}
In next post I’ll add some more complex examples.
Please do let me know if you have any suggestions or any query on JSON in comment section. I’ll try to resolve it.

