Java – org.json

Also see Java Json – Simple

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

Build JSON using a bean

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

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

One thought on “Java – org.json

  • January 4, 2017 at 1:53 pm
    Permalink

    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?

    Reply

Leave a Reply

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