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

Build JSON

We now build a json string for a genre

Build JSON using a bean

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

Leave a Reply

Your email address will not be published. Required fields are marked *