Java: org.json

Overview of The API Classes

org.json has classes to parse and write json string. It also converts between json and xml, HTTP header, Cookies, and CDF. The main classes are:

  1. 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
  2. org.json.JSONTokener - This class parses a JSON string and is also used internally by the JSONObject and JSONArray classes to parse JSON Strings
  3. org.json.JSONArray - This class stores an ordered sequence of values. Externally it represents a JSON Array
  4. org.json.JSONWriter - This class represents 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.
  5. 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.
  6. org.json.Cookie - This class has method to convert a web browser cookie to a JSONObject and back.
  7. org.json.CookieList - This class has method to convert a list of cookies to JSONObject and back. Lets see some examples

Parse JSON

This examples 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

Lets 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

Lets look at an example of how to use the java.json.CDL class to convert a jsonarray 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();
		}
	}
}

(Note: This article’s original links is here )

 Java: Json Simple Java: Date And Calendar 

Comments