Java – Json Simple

Overview of The API Classes

Json Simple is, as the name suggest, a very simple API. The API itself is made up of around 13 classes. The main classes are :

  1. JSONParser – This parses Json text. It takes in a java.io.Reader or a String Object. It is also possible to pass a ContentHandler or ContainerHandler to the parser.
  2. JSONObject – This is a java representation of JSON string. It stores key value pairs. JsonObject extends HashMap. It has method to encode a map to a JSON text (writeJSONString(Map map, Writer out))
  3. JSONArray – Represents a collection. It extends an ArrayList. It implements the JSONAware and JSONStreamAware interface
  4. JSONValue – This class has methods to parse JSON string into Java objects. It uses the JSONParser to do so. It has methods to write JSON string from many java types (writeJSONString(Object value, Writer out)). It also has methods to escapte special characters using the escape(String s) method. This method escapes quotes, \, /, \r, \n, \b, \f, \t and other control characters (U+0000 through U+001F)
  5. JSONAware – Beans that support output to JSON form should implement this interface.

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

import java.io.IOException;
import java.net.URL;

import org.apache.commons.io.IOUtils;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
import org.json.simple.parser.ParseException;

public class ParseJson1 {

	public static void main(String[] args) {
		String url = "http://freemusicarchive.org/api/get/genres.json?api_key=60BLHNQCAOUFPIBZ&limit=2";
		/*
		 * {"title":"Free Music Archive - Genres","message":"","errors":[],"total" : "161","total_pages":81,"page":1,"limit":"2",
		 * "dataset":
		 * [{"genre_id": "1","genre_parent_id":"38","genre_title":"Avant-Garde" ,"genre_handle": "Avant-Garde","genre_color":"#006666"},
		 * {"genre_id":"2","genre_parent_id" :null,"genre_title":"International","genre_handle":"International","genre_color":"#CC3300"}]}
		 */
		try {
			String genreJson = IOUtils.toString(new URL(url));
			JSONObject genreJsonObject = (JSONObject) JSONValue.parseWithException(genreJson);
			// get the title
			System.out.println(genreJsonObject.get("title"));
			// get the data
			JSONArray genreArray = (JSONArray) genreJsonObject.get("dataset");
			// get the first genre
			JSONObject firstGenre = (JSONObject) genreArray.get(0);
			System.out.println(firstGenre.get("genre_title"));
		} catch (IOException | ParseException e) {
			e.printStackTrace();
		}
	}
}

Build JSON

We now build a json string for a genre

package com.studytrails.json.jsonsimple;

import org.json.simple.JSONObject;
import org.json.simple.JSONValue;

public class BuildJson1 {

	public static void main(String[] args) {
		JSONObject dataset = new JSONObject();
		dataset.put("genre_id", 1);
		dataset.put("genre_parent_id", null);
		dataset.put("genre_title", "International");
		dataset.put("genre_handle", "International");
		dataset.put("genre_color", "#CC3300");
		System.out.println(dataset.toJSONString());
		// if you want to escape characters
		System.out.println(JSONValue.escape(dataset.toJSONString()));
	}

}

Build JSON using a bean

Lets look at how to build the same JSON string as above but using a bean for the genre

import java.util.HashMap;
import java.util.Map;

import org.json.simple.JSONAware;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;

public class BuildJson2 {

	public static void main(String[] args) {
		BuildJson2 json2 = new BuildJson2();
		GenreBean bean = json2.new GenreBean();
		bean.setGenre_title("International");
		bean.setGenre_color("#CC3300");
		bean.setGenre_handle("International");
		bean.setGenre_id(1);
		System.out.println(JSONValue.toJSONString(bean));
	}

	class GenreBean implements JSONAware {

		int genre_id;
		int genre_parent_id;
		String genre_handle;
		String genre_title;
		String genre_color;

		@Override
		public String toJSONString() {
			Map<Object , Object> genreBeanJsonMap = new HashMap<Object , Object>();
			genreBeanJsonMap.put("genre_id", getGenre_id());
			genreBeanJsonMap.put("genre_parent_id", getGenre_parent_id());
			genreBeanJsonMap.put("genre_handle", getGenre_handle());
			genreBeanJsonMap.put("genre_title", getGenre_handle());
			genreBeanJsonMap.put("genre_color", getGenre_color());
			return JSONObject.toJSONString(genreBeanJsonMap);
		}

		public int getGenre_id() {
			return genre_id;
		}

		public void setGenre_id(int genre_id) {
			this.genre_id = genre_id;
		}

		public int getGenre_parent_id() {
			return genre_parent_id;
		}

		public void setGenre_parent_id(int genre_parent_id) {
			this.genre_parent_id = genre_parent_id;
		}

		public String getGenre_handle() {
			return genre_handle;
		}

		public void setGenre_handle(String genre_handle) {
			this.genre_handle = genre_handle;
		}

		public String getGenre_title() {
			return genre_title;
		}

		public void setGenre_title(String genre_title) {
			this.genre_title = genre_title;
		}

		public String getGenre_color() {
			return genre_color;
		}

		public void setGenre_color(String genre_color) {
			this.genre_color = genre_color;
		}

	}
}

Leave a Comment