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.math.BigDecimal;
import java.math.BigInteger;
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> 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* { * "a":{"b":"c"} * } ** and this JSONPointer string: *
* "/a/b" ** Then this method will return the String "c". * A JSONPointerException may be thrown from code called by this method. * * @param jsonPointer string that can be used to create a JSONPointer * @return the item matched by the JSONPointer, otherwise null */ public Object query(String jsonPointer) { return new JSONPointer(jsonPointer).queryFrom(this); } /** * Queries and returns a value from this object using {@code jsonPointer}, or * returns null if the query fails due to a missing key. * * @param jsonPointer the string representation of the JSON pointer * @return the queried value or {@code null} * @throws IllegalArgumentException if {@code jsonPointer} has invalid syntax */ public Object optQuery(String jsonPointer) { JSONPointer pointer = new JSONPointer(jsonPointer); try { return pointer.queryFrom(this); } catch (JSONPointerException e) { return null; } } /** * Produce a string in double quotes with backslash sequences in all the * right places. A backslash will be inserted within , producing <\/, * allowing JSON text to be delivered in HTML. In JSON text, a string cannot * contain a control character or an unescaped quote or backslash. * * @param string * A String * @return A String correctly formatted for insertion in a JSON text. */ public static String quote(String string) { StringWriter sw = new StringWriter(); synchronized (sw.getBuffer()) { try { return quote(string, sw).toString(); } catch (IOException ignored) { // will never happen - we are writing to a string writer return ""; } } } public static Writer quote(String string, Writer w) throws IOException { if (string == null || string.length() == 0) { w.write("\"\""); return w; } char b; char c = 0; String hhhh; int i; int len = string.length(); w.write('"'); for (i = 0; i < len; i += 1) { b = c; c = string.charAt(i); switch (c) { case '\\': case '"': w.write('\\'); w.write(c); break; case '/': if (b == '<') { w.write('\\'); } w.write(c); break; case '\b': w.write("\\b"); break; case '\t': w.write("\\t"); break; case '\n': w.write("\\n"); break; case '\f': w.write("\\f"); break; case '\r': w.write("\\r"); break; default: if (c < ' ' || (c >= '\u0080' && c < '\u00a0') || (c >= '\u2000' && c < '\u2100')) { w.write("\\u"); hhhh = Integer.toHexString(c); w.write("0000", 0, 4 - hhhh.length()); w.write(hhhh); } else { w.write(c); } } } w.write('"'); return w; } /** * Remove a name and its value, if present. * * @param key * The name to be removed. * @return The value that was associated with the name, or null if there was * no value. */ public Object remove(String key) { return this.map.remove(key); } /** * Determine if two JSONObjects are similar. * They must contain the same set of names which must be associated with * similar values. * * @param other The other JSONObject * @return true if they are equal */ public boolean similar(Object other) { try { if (!(other instanceof JSONObject)) { return false; } Set
* 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 (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 {
(left
* brace) and ending with }
(right
* brace).
* @throws JSONException
* If the value is or contains an invalid number.
*/
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) {
// not all Numbers may match actual JSON Numbers. i.e. Fractions or Complex
final String numberAsString = numberToString((Number) value);
try {
// Use the BigDecimal constructor for it's parser to validate the format.
new BigDecimal(numberAsString);
// Close enough to a JSON number that we will return it unquoted
return numberAsString;
} catch (NumberFormatException ex){
// The Number value is not a valid JSON number.
// Instead we will quote it as a string
return quote(numberAsString);
}
}
if (value instanceof Boolean || value instanceof JSONObject
|| value instanceof JSONArray) {
return value.toString();
}
if (value instanceof Map) {
Map, ?> map = (Map, ?>) value;
return new JSONObject(map).toString();
}
if (value instanceof Collection) {
Collection> coll = (Collection>) value;
return new JSONArray(coll).toString();
}
if (value.getClass().isArray()) {
return new JSONArray(value).toString();
}
if(value instanceof Enum>){
return quote(((Enum>)value).name());
}
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(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 || object instanceof Enum) {
return object;
}
if (object instanceof Collection) {
Collection> coll = (Collection>) object;
return new JSONArray(coll);
}
if (object.getClass().isArray()) {
return new JSONArray(object);
}
if (object instanceof Map) {
Map, ?> map = (Map, ?>) object;
return new JSONObject(map);
}
Package objectPackage = object.getClass().getPackage();
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 (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. * * @return The writer. * @throws JSONException */ public Writer write(Writer writer) throws JSONException { return this.write(writer, 0, 0); } 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 JSONString) { Object o; try { o = ((JSONString) value).toJSONString(); } catch (Exception e) { throw new JSONException(e); } writer.write(o != null ? o.toString() : quote(value.toString())); } else if (value instanceof Number) { // not all Numbers may match actual JSON Numbers. i.e. fractions or Imaginary final String numberAsString = numberToString((Number) value); try { // Use the BigDecimal constructor for it's parser to validate the format. @SuppressWarnings("unused") BigDecimal testNum = new BigDecimal(numberAsString); // Close enough to a JSON number that we will use it unquoted writer.write(numberAsString); } catch (NumberFormatException ex){ // The Number value is not a valid JSON number. // Instead we will quote it as a string quote(numberAsString, writer); } } else if (value instanceof Boolean) { writer.write(value.toString()); } else if (value instanceof Enum>) { writer.write(quote(((Enum>)value).name())); } 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) { Map, ?> map = (Map, ?>) value; new JSONObject(map).write(writer, indentFactor, indent); } else if (value instanceof Collection) { Collection> coll = (Collection>) value; new JSONArray(coll).write(writer, indentFactor, indent); } else if (value.getClass().isArray()) { new JSONArray(value).write(writer, indentFactor, indent); } else { quote(value.toString(), writer); } return writer; } static final void indent(Writer writer, 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
*/
public Writer write(Writer writer, int indentFactor, int indent)
throws JSONException {
try {
boolean commanate = false;
final int length = this.length();
Iterator
* Warning: This method assumes that the data structure is acyclical.
*
* @return a java.util.Map containing the entries of this object
*/
public Map