-
Notifications
You must be signed in to change notification settings - Fork 2.6k
Home
JSON-Java is a reference application for reading and writing JSON docs in Java. It was written by Douglas Crockford, who first specified the JSON document format. It works by parsing and storing JSON text inside of POJOs - Plain Old Java Objects. This allows your Java code to navigate into the doc, read, update, and write the JSON document.
The primary purpose of this project is to show how to parse and emit JSON documents in Java. There are two primary classes:
- JSONObject: Parse a JSON object from a String, update the JSON, and emit it as a String.
- JSONArray: Parse a JSON array from a String, update the JSON, and emit it as a String.
For the purposes of this project, a JSON doc is a valid JSON text string that begins with '{' or '['. JSON text that consists entirely of a string or primitive type is represented by the corresponding Java type and is not parsed or emitted by this library. If the text string begins with '{', it should be parsed by creating a new JSONObject(String). If the text begins with '[', it should be parsed by creating a new JSONArray(String).
- Create a new JSONObject() and populate the instance by calling put*(), putOpt*(), append(), and accumulate() API methods.
- Create a new JSONArray() and populate the instance by calling put*(), putOpt*(), putAll(), and addAll() API methods.
- JSON text that is accessed via a Reader object can be parsed with a JSONTokener. Here is an example using a JSONObject. The reader should be closed by the calling code after the JSONObject is created.
Reader reader;
/* initialize the reader */
JSONObject jsonObject = new JSONObject(new JSONTokener(reader));
Calling jsonObject.toString() or jsonArray.toString() will cause the instance to emit its contents as a syntactically correct JSON document without blank-space chars. An empty JSONObject will emit "{}". An empty JSONArray will emit "[]". Formatted output can be obtained by calling jsonObject.toString(int) or jsonArray.toString(int), where the int parameter indicates the indentation.