Parse JSON for Java using org.json
org.json has classes to parse Json for Java. It also converts between JSON and XML, HTTP header, Cookies, and CDF. The main classes are:
- org.json.JSONObject – This class stores unordered key-value pairs. The value can be Boolean, JSONArray, Number, String or JSONObject.NULL. It has constructors to take in a JSON string and store it as key-value pairs. It also has constructors that take in a Map, a bean or a String
- org.json.JSONTokener – This class parses a JSON string and is also used internally by the JSONObject and JSONArray classes to parse JSON Strings
- org.json.JSONArray – This class stores an ordered sequence of values. Externally it represents a JSON Array
- org.json.JSONWriter – This class represents a method to produce JSON text. It has an append(String) method to append a string to a JSON text, key(String) and value(String) method to add key and values to JSON string. It can also write an array.
- org.json.CDL– This class has methods to convert comma delimited text to JSONArray and a JSONArray to a comma delimited text. The array contains rows of comma separed strings, with rows separated by newline. The first row contains names.
- org.json.Cookie – This class has method to convert a web browser cookie to a JSONObject and back.
- org.json.CookieList – This class has method to convert a list of cookies to JSONObject and back.
Let’s see some examples
Parse JSON
This example shows how to parse a JSON string. The JSON string in this example is a list of genres (limited to 2) from freemusicarchive.org
package com.studytriails.json.orgjson;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import org.apache.commons.io.IOUtils;
import org.json.JSONObject;
import org.json.simple.JSONArray;
public class ParseJson1 {
public static void main(String[] args) throws MalformedURLException, IOException {
String url = "http://freemusicarchive.org/api/get/genres.json?api_key=60BLHNQCAOUFPIBZ&limit=2";
String genreJson = IOUtils.toString(new URL(url));
JSONObject json = new JSONObject(genreJson);
// get the title
System.out.println(json.get("title"));
// get the data
JSONArray genreArray = (JSONArray) json.get("dataset");
// get the first genre
JSONObject firstGenre = (JSONObject) genreArray.get(0);
System.out.println(firstGenre.get("genre_title"));
}
}
Build JSON using a bean
Let’s look at how to build the same JSON string as above but using a bean for the genre
package com.studytriails.json.orgjson;
import org.json.JSONObject;
public class BuildJson1 {
public static void main(String[] args) {
JSONObject dataset = new JSONObject();
dataset.put("genre_id", 1);
dataset.put("genre_parent_id", JSONObject.NULL);
dataset.put("genre_title", "International");
// use the accumulate function to add to an existing value. The value
// will now be converted to a list
dataset.accumulate("genre_title", "Pop");
// append to the key
dataset.append("genre_title", "slow");
dataset.put("genre_handle", "International");
dataset.put("genre_color", "#CC3300");
// get the json array for a string
System.out.println(dataset.getJSONArray("genre_title"));
// prints ["International","Pop","slow"]
// increment a number by 1
dataset.increment("genre_id");
// quote a string allowing the json to be delivered within html
System.out.println(JSONObject.quote(dataset.toString()));
// prints
// "{\"genre_color\":\"#CC3300\",\"genre_title\":[\"International\",\"Pop\",\"slow\"],
// \"genre_handle\":\"International\",\"genre_parent_id\":null,\"genre_id\":2}"
}
}
Creating a CSV from JsonArray
Let’s look at an example of how to use the java.json.CDL class to convert a JSON array to a CSV
package com.studytriails.json.orgjson;
import java.io.IOException;
import java.net.URL;
import org.apache.commons.io.IOUtils;
import org.json.CDL;
import org.json.JSONArray;
import org.json.JSONObject;
public class JsonToCsv {
public static void main(String[] args) {
String url = "http://freemusicarchive.org/api/get/genres.json?api_key=60BLHNQCAOUFPIBZ&limit=10";
try {
String genreJson = IOUtils.toString(new URL(url));
JSONObject json = new JSONObject(genreJson);
System.out.println(CDL.toString(new JSONArray(json.get("dataset").toString())));
} catch (IOException e) {
e.printStackTrace();
}
}
}
Hello Mithil,
I am trying to get a better understanding of JAVA org.json.JSONObject
I have three beans that handle my remote MySQL connectivity and issue of SQL statement to select * from the table.
I have one bean that retrieves the remote data and converts it into a JSON array that I need to modify to produce a JSON string that can be referenced in web.xml mapped URL.
Please, would you have any advice on where to find guidance or tutorials to accomplish this?