get and opt methods for accessing the
* values by name, and put methods for adding or replacing values
* by name. The values can be any of these types: Boolean,
* JSONArray, JSONObject, Number,
* String, or the JSONObject.NULL object. A JSONObject
* constructor can be used to convert an external form JSON text into an
* internal form whose values can be retrieved with the get and
* opt methods, or to convert values into a JSON text using the
* put and toString methods. A get method
* returns a value if one can be found, and throws an exception if one cannot be
* found. An opt method returns a default value instead of throwing
* an exception, and so is useful for obtaining optional values.
*
* The generic get() and opt() methods return an
* object, which you can cast or query for type. There are also typed
* get and opt methods that do type checking and type
* coercion for you. The opt methods differ from the get methods in that they do
* not throw. Instead, they return a specified value, such as null.
*
* The put methods add or replace values in an object. For example,
*
*
* myString = new JSONObject().put("JSON", "Hello, World!").toString();
*
*
* produces the string {"JSON": "Hello, World"}.
*
* The texts produced by the toString methods strictly conform to
* the JSON syntax rules. The constructors are more forgiving in the texts they
* will accept:
*
, (comma) may appear just
* before the closing brace.' (single
* quote).{ } [ ] / \ : , # and if they do not look like numbers and if
* they are not the reserved words true, false, or
* null.NULL object than to use Java's null value.
* JSONObject.NULL.equals(null) returns true.
* JSONObject.NULL.toString() returns "null".
*/
public static final Object NULL = new Null();
/**
* Construct an empty JSONObject.
*/
public JSONObject() {
super();
}
/**
* Construct a JSONObject from a subset of another JSONObject. An array of
* strings is used to identify the keys that should be copied. Missing keys
* are ignored.
*
* @param jo A JSONObject.
* @param names An array of strings.
*/
public JSONObject(final JSONObject jo, final String[] names) {
this();
for (final String name : names)
try {
putOnce(name, jo.opt(name));
} catch (final Exception ignore) {}
}
/**
* Construct a JSONObject from a JSONTokener.
*
* @param x A JSONTokener object containing the source string.
* @throws JSONException If there is a syntax error in the source string or
* a duplicated key.
*/
public JSONObject(final JSONTokener x) throws JSONException {
this();
char c;
String key;
if (x.nextClean() != '{')
throw x.syntaxError("A JSONObject text must begin with '{'");
for (;;) {
c = x.nextClean();
switch (c) {
case 0:
throw x.syntaxError("A JSONObject text must end with '}'");
case '}':
return;
default:
x.back();
key = x.nextValue().toString();
}
// The key is followed by ':'.
c = x.nextClean();
if (c != ':')
throw x.syntaxError("Expected a ':' after a key");
putOnce(key, x.nextValue());
// Pairs are separated by ','.
switch (x.nextClean()) {
case ';':
case ',':
if (x.nextClean() == '}')
return;
x.back();
break;
case '}':
return;
default:
throw x.syntaxError("Expected a ',' or '}'");
}
}
}
/**
* Construct a JSONObject from a Map.
*
* @param map A map object that can be used to initialize the contents of
* the JSONObject.
*/
public JSONObject(final Map map) {
this();
if (map != null)
for (final Entry e : map.entrySet()) {
final Object value = e.getValue();
if (value != null)
super.put(String.valueOf(e.getKey()), wrap(value));
}
}
/**
* Construct a JSONObject from an Object using bean getters. It reflects on
* all of the public methods of the object. For each of the methods with no
* parameters and a name starting with "get" or
* "is" followed by an uppercase letter, the method is invoked,
* and a key and the value returned from the getter method are put into the
* new JSONObject. The key is formed by removing the "get" or
* "is" prefix. If the second remaining character is not upper
* case, then the first character is converted to lower case. For example,
* if an object has a method named "getName", and if the result
* of calling object.getName() is "Larry Fine",
* then the JSONObject will contain "name": "Larry Fine".
*
* @param bean An object that has getter methods that should be used to make
* a JSONObject.
*/
public JSONObject(final Object bean) {
this();
populateMap(bean);
}
/**
* Construct a JSONObject from an Object, using reflection to find the
* public members. The resulting JSONObject's keys will be the strings from
* the names array, and the values will be the field values associated with
* those keys in the object. If a key is not found or not visible, then it
* will not be copied into the new JSONObject.
*
* @param object An object that has fields that should be used to make a
* JSONObject.
* @param names An array of strings, the names of the fields to be obtained
* from the object.
*/
public JSONObject(final Object object, final String names[]) {
this();
final Class c = object.getClass();
for (final String name : names)
try {
putOpt(name, c.getField(name).get(object));
} catch (final Exception ignore) {}
}
/**
* Construct a JSONObject from a source JSON text string. This is the most
* commonly used JSONObject constructor.
*
* @param source A string beginning with { (left
* brace) and ending with }
* (right brace).
* @exception JSONException If there is a syntax error in the source string
* or a duplicated key.
*/
public JSONObject(final String source) throws JSONException {
this(new JSONTokener(source));
}
/**
* Construct a JSONObject from a ResourceBundle.
*
* @param baseName The ResourceBundle base name.
* @param locale The Locale to load the ResourceBundle for.
* @throws JSONException If any JSONExceptions are detected.
*/
public JSONObject(final String baseName, final Locale locale)
throws JSONException
{
this();
final ResourceBundle bundle = ResourceBundle.getBundle(baseName, locale,
Thread.currentThread().getContextClassLoader());
// Iterate through the keys in the bundle.
final Enumeration
* Warning: This method assumes that the data structure is acyclical.
*
* @return a printable, displayable, portable, transmittable representation
* of the object, beginning with { (left
* brace) and ending with } (right
* brace).
*/
@Override
public String toString() {
try {
return this.toString(0);
} catch (final Exception e) {
return null;
}
}
/**
* Make a prettyprinted JSON text of this JSONObject.
*
* Warning: This method assumes that the data structure is acyclical.
*
* @param indentFactor The number of spaces to add to each level of
* indentation.
* @return a printable, displayable, portable, transmittable representation
* of the object, beginning with { (left
* brace) and ending with } (right
* brace).
* @throws JSONException If the object contains an invalid number.
*/
public String toString(final int indentFactor) throws JSONException {
final StringWriter w = new StringWriter();
synchronized (w.getBuffer()) {
return this.write(w, indentFactor, 0).toString();
}
}
/**
* Make a JSON text of an Object value. If the object has an
* value.toJSONString() method, then that method will be used to produce the
* JSON text. The method is required to produce a strictly conforming text.
* If the object does not contain a toJSONString method (which is the most
* common case), then a text will be produced by other means. If the value
* is an array or Collection, then a JSONArray will be made from it and its
* toJSONString method will be called. If the value is a MAP, then a
* JSONObject will be made from it and its toJSONString method will be
* called. Otherwise, the value's toString method will be called, and the
* result will be quoted.
*
* Warning: This method assumes that the data structure is acyclical.
*
* @param value The value to be serialized.
* @return a printable, displayable, transmittable representation of the
* object, beginning with { (left
* brace) and ending with } (right
* brace).
* @throws JSONException If the value is or contains an invalid number.
*/
public static String valueToString(final Object value)
throws JSONException
{
if (value == null || value.equals(null))
return "null";
if (value instanceof JSONString) {
Object object;
try {
object = ((JSONString)value).toJSONString();
} catch (final Exception e) {
throw new JSONException(e);
}
if (object instanceof String)
return (String)object;
throw new JSONException("Bad value from toJSONString: " + object);
}
if (value instanceof Number)
return numberToString((Number)value);
if (value instanceof Boolean || value instanceof JSONObject
|| value instanceof JSONArray)
return value.toString();
if (value instanceof Map) {
final Map map = (Map)value;
return new JSONObject(map).toString();
}
if (value instanceof Collection) {
final Collection coll = (Collection)value;
return new JSONArray(coll).toString();
}
if (value.getClass().isArray())
return new JSONArray(value).toString();
return quote(value.toString());
}
/**
* Wrap an object, if necessary. If the object is null, return the NULL
* object. If it is an array or collection, wrap it in a JSONArray. If it is
* a map, wrap it in a JSONObject. If it is a standard property (Double,
* String, et al) then it is already wrapped. Otherwise, if it comes from
* one of the java packages, turn it into a string. And if it doesn't, try
* to wrap it in a JSONObject. If the wrapping fails, then null is returned.
*
* @param object The object to wrap
* @return The wrapped value
*/
public static Object wrap(final Object object) {
try {
if (object == null)
return NULL;
if (object instanceof JSONObject || object instanceof JSONArray
|| NULL.equals(object) || object instanceof JSONString
|| object instanceof Byte || object instanceof Character
|| object instanceof Short || object instanceof Integer
|| object instanceof Long || object instanceof Boolean
|| object instanceof Float || object instanceof Double
|| object instanceof String || object instanceof BigInteger
|| object instanceof BigDecimal)
return object;
if (object instanceof Map) {
final Map map = (Map)object;
return new JSONObject(map);
}
if (object instanceof Collection) {
final Collection coll = (Collection)object;
return new JSONArray(coll);
}
if (object.getClass().isArray())
return new JSONArray(object);
final Package objectPackage = object.getClass().getPackage();
final String objectPackageName = objectPackage != null
? objectPackage.getName() : "";
if (objectPackageName.startsWith("java.")
|| objectPackageName.startsWith("javax.")
|| object.getClass().getClassLoader() == null)
return object.toString();
return new JSONObject(object);
} catch (final Exception exception) {
return null;
}
}
/**
* Write the contents of the JSONObject as JSON text to a writer. For
* compactness, no whitespace is added.
*
* Warning: This method assumes that the data structure is acyclical. * * @param writer The writer * @return The writer. * @throws JSONException If there was an error in writing */ public Writer write(final Writer writer) throws JSONException { return this.write(writer, 0, 0); } static final Writer writeValue(final Writer writer, final Object value, final int indentFactor, final int indent) throws JSONException, IOException { if (value == null || value.equals(null)) writer.write("null"); else if (value instanceof JSONObject) ((JSONObject)value).write(writer, indentFactor, indent); else if (value instanceof JSONArray) ((JSONArray)value).write(writer, indentFactor, indent); else if (value instanceof Map) { final Map map = (Map)value; new JSONObject(map).write(writer, indentFactor, indent); } else if (value instanceof Collection) { final Collection coll = (Collection)value; new JSONArray(coll).write(writer, indentFactor, indent); } else if (value.getClass().isArray()) new JSONArray(value).write(writer, indentFactor, indent); else if (value instanceof Number) writer.write(numberToString((Number)value)); else if (value instanceof Boolean) writer.write(value.toString()); else if (value instanceof JSONString) { Object o; try { o = ((JSONString)value).toJSONString(); } catch (final Exception e) { throw new JSONException(e); } writer.write(o != null ? o.toString() : quote(value.toString())); } else quote(value.toString(), writer); return writer; } static final void indent(final Writer writer, final int indent) throws IOException { for (int i = 0; i < indent; i += 1) writer.write(' '); } /** * Write the contents of the JSONObject as JSON text to a writer. For * compactness, no whitespace is added. *
* Warning: This method assumes that the data structure is acyclical.
*
* @param writer Writes the serialized JSON
* @param indentFactor The number of spaces to add to each level of
* indentation.
* @param indent The indention of the top level.
* @return The writer.
* @throws JSONException If there was an error during writing
*/
public Writer write(final Writer writer, final int indentFactor,
final int indent) throws JSONException
{
try {
boolean commanate = false;
final int length = length();
final Iterator