package org.json;
/*
Copyright (c) 2002 JSON.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
The Software shall be used for Good, not Evil.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Collection;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import java.util.ResourceBundle;
import java.util.Set;
/**
* A JSONObject is an unordered collection of name/value pairs. Its external
* form is a string wrapped in curly braces with colons between the names and
* values, and commas between the values and names. The internal form is an
* object having 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() {
this.map = new HashMap"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(Object bean) {
this();
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(Object object, String names[]) {
this();
Class extends Object> c = object.getClass();
for (int i = 0; i < names.length; i += 1) {
String name = names[i];
try {
this.putOpt(name, c.getField(name).get(object));
} catch (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(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(String baseName, Locale locale) throws JSONException {
this();
ResourceBundle bundle = ResourceBundle.getBundle(baseName, locale,
Thread.currentThread().getContextClassLoader());
// Iterate through the keys in the bundle.
Enumeration> keys = bundle.getKeys();
while (keys.hasMoreElements()) {
Object key = keys.nextElement();
if (key instanceof String) {
// Go through the path, ensuring that there is a nested JSONObject for each
// segment except the last. Add the value using the last segment's name into
// the deepest nested JSONObject.
String[] path = ((String) key).split("\\.");
int last = path.length - 1;
JSONObject target = this;
for (int i = 0; i < last; i += 1) {
String segment = path[i];
JSONObject nextTarget = target.optJSONObject(segment);
if (nextTarget == null) {
nextTarget = new JSONObject();
target.put(segment, nextTarget);
}
target = nextTarget;
}
target.put(path[last], bundle.getString((String) key));
}
}
}
/**
* Accumulate values under a key. It is similar to the put method except
* that if there is already an object stored under the key then a JSONArray
* is stored under the key to hold all of the accumulated values. If there
* is already a JSONArray, then the new value is appended to it. In
* contrast, the put method replaces the previous value.
*
* If only one value is accumulated that is not a JSONArray, then the result
* will be the same as using put. But if multiple values are accumulated,
* then the result will be like append.
*
* @param key
* A key string.
* @param value
* An object to be accumulated under the key.
* @return this.
* @throws JSONException
* If the value is an invalid number or if the key is null.
*/
public JSONObject accumulate(String key, Object value) throws JSONException {
testValidity(value);
Object object = this.opt(key);
if (object == null) {
this.put(key,
value instanceof JSONArray ? new JSONArray().put(value)
: value);
} else if (object instanceof JSONArray) {
((JSONArray) object).put(value);
} else {
this.put(key, new JSONArray().put(object).put(value));
}
return this;
}
/**
* Append values to the array under a key. If the key does not exist in the
* JSONObject, then the key is put in the JSONObject with its value being a
* JSONArray containing the value parameter. If the key was already
* associated with a JSONArray, then the value parameter is appended to it.
*
* @param key
* A key string.
* @param value
* An object to be accumulated under the key.
* @return this.
* @throws JSONException
* If the key is null or if the current value associated with
* the key is not a JSONArray.
*/
public JSONObject append(String key, Object value) throws JSONException {
testValidity(value);
Object object = this.opt(key);
if (object == null) {
this.put(key, new JSONArray().put(value));
} else if (object instanceof JSONArray) {
this.put(key, ((JSONArray) object).put(value));
} else {
throw new JSONException("JSONObject[" + key
+ "] is not a JSONArray.");
}
return this;
}
/**
* Produce a string from a double. The string "null" will be returned if the
* number is not finite.
*
* @param d
* A double.
* @return A String.
*/
public static String doubleToString(double d) {
if (Double.isInfinite(d) || Double.isNaN(d)) {
return "null";
}
// Shave off trailing zeros and decimal point, if possible.
String string = Double.toString(d);
if (string.indexOf('.') > 0 && string.indexOf('e') < 0
&& string.indexOf('E') < 0) {
while (string.endsWith("0")) {
string = string.substring(0, string.length() - 1);
}
if (string.endsWith(".")) {
string = string.substring(0, string.length() - 1);
}
}
return string;
}
/**
* Get the value object associated with a key.
*
* @param key
* A key string.
* @return The object associated with the key.
* @throws JSONException
* if the key is not found.
*/
public Object get(String key) throws JSONException {
if (key == null) {
throw new JSONException("Null key.");
}
Object object = this.opt(key);
if (object == null) {
throw new JSONException("JSONObject[" + quote(key) + "] not found.");
}
return object;
}
/**
* Get the boolean value associated with a key.
*
* @param key
* A key string.
* @return The truth.
* @throws JSONException
* if the value is not a Boolean or the String "true" or
* "false".
*/
public boolean getBoolean(String key) throws JSONException {
Object object = this.get(key);
if (object.equals(Boolean.FALSE)
|| (object instanceof String && ((String) object)
.equalsIgnoreCase("false"))) {
return false;
} else if (object.equals(Boolean.TRUE)
|| (object instanceof String && ((String) object)
.equalsIgnoreCase("true"))) {
return true;
}
throw new JSONException("JSONObject[" + quote(key)
+ "] is not a Boolean.");
}
/**
* Get the double value associated with a key.
*
* @param key
* A key string.
* @return The numeric value.
* @throws JSONException
* if the key is not found or if the value is not a Number
* object and cannot be converted to a number.
*/
public double getDouble(String key) throws JSONException {
Object object = this.get(key);
try {
return object instanceof Number ? ((Number) object).doubleValue()
: Double.parseDouble((String) object);
} catch (Exception e) {
throw new JSONException("JSONObject[" + quote(key)
+ "] is not a number.");
}
}
/**
* Get the int value associated with a key.
*
* @param key
* A key string.
* @return The integer value.
* @throws JSONException
* if the key is not found or if the value cannot be converted
* to an integer.
*/
public int getInt(String key) throws JSONException {
Object object = this.get(key);
try {
return object instanceof Number ? ((Number) object).intValue()
: Integer.parseInt((String) object);
} catch (Exception e) {
throw new JSONException("JSONObject[" + quote(key)
+ "] is not an int.");
}
}
/**
* Get the JSONArray value associated with a key.
*
* @param key
* A key string.
* @return A JSONArray which is the value.
* @throws JSONException
* if the key is not found or if the value is not a JSONArray.
*/
public JSONArray getJSONArray(String key) throws JSONException {
Object object = this.get(key);
if (object instanceof JSONArray) {
return (JSONArray) object;
}
throw new JSONException("JSONObject[" + quote(key)
+ "] is not a JSONArray.");
}
/**
* Get the JSONObject value associated with a key.
*
* @param key
* A key string.
* @return A JSONObject which is the value.
* @throws JSONException
* if the key is not found or if the value is not a JSONObject.
*/
public JSONObject getJSONObject(String key) throws JSONException {
Object object = this.get(key);
if (object instanceof JSONObject) {
return (JSONObject) object;
}
throw new JSONException("JSONObject[" + quote(key)
+ "] is not a JSONObject.");
}
/**
* Get the long value associated with a key.
*
* @param key
* A key string.
* @return The long value.
* @throws JSONException
* if the key is not found or if the value cannot be converted
* to a long.
*/
public long getLong(String key) throws JSONException {
Object object = this.get(key);
try {
return object instanceof Number ? ((Number) object).longValue()
: Long.parseLong((String) object);
} catch (Exception e) {
throw new JSONException("JSONObject[" + quote(key)
+ "] is not a long.");
}
}
/**
* Get an array of field names from a JSONObject.
*
* @return An array of field names, or null if there are no names.
*/
public static String[] getNames(JSONObject jo) {
int length = jo.length();
if (length == 0) {
return null;
}
Iterator
* 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).
*/
public String toString() {
try {
return this.toString(0);
} catch (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(int indentFactor) throws JSONException {
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
* Warning: This method assumes that the data structure is acyclical.
*
* @return The writer.
* @throws JSONException
*/
public Writer write(Writer writer) throws JSONException {
return this.write(writer, 0, 0);
}
@SuppressWarnings("unchecked")
static final Writer writeValue(Writer writer, Object value,
int indentFactor, 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) {
new JSONObject((Map
* Warning: This method assumes that the data structure is acyclical.
*
* @return The writer.
* @throws JSONException
*/
Writer write(Writer writer, int indentFactor, int indent)
throws JSONException {
try {
boolean commanate = false;
final int length = this.length();
Iterator{
(left
* brace) and ending with }
(right
* brace).
* @throws JSONException
* If the value is or contains an invalid number.
*/
@SuppressWarnings("unchecked")
public static String valueToString(Object value) throws JSONException {
if (value == null || value.equals(null)) {
return "null";
}
if (value instanceof JSONString) {
Object object;
try {
object = ((JSONString) value).toJSONString();
} catch (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) {
return new JSONObject((Map