org.opencms.json.JSONObject Maven / Gradle / Ivy
Show all versions of opencms-core Show documentation
/*
* This library is part of OpenCms -
* the Open Source Content Management System
*
* Copyright (c) Alkacon Software GmbH & Co. KG (http://www.alkacon.com)
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* For further information about Alkacon Software GmbH & Co. KG, please see the
* company website: http://www.alkacon.com
*
* For further information about OpenCms, please see the
* project website: http://www.opencms.org
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* This file is based on:
* org.json.JSONObject
* from the JSON in Java implementation.
*
* 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.
*/
package org.opencms.json;
import java.io.IOException;
import java.io.Writer;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
/**
* 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
* conversion for you.
*
* The put
methods adds values to 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:
*
* - An extra
,
(comma) may appear just
* before the closing brace.
* - Strings may be quoted with
'
(single
* quote).
* - Strings do not need to be quoted at all if they do not begin with a quote
* or single quote, and if they do not contain leading or trailing spaces,
* and if they do not contain any of these characters:
*
{ } [ ] / \ : , = ; #
and if they do not look like numbers
* and if they are not the reserved words true
,
* false
, or null
.
* - Keys can be followed by
=
or =>
as well as
* by :
.
* - Values can be followed by
;
(semicolon) as
* well as by ,
(comma).
* - Numbers may have the
0-
(octal) or
* 0x-
(hex) prefix.
* - Comments written in the slashshlash, slashstar, and hash conventions
* will be ignored.
*
*
*/
public class JSONObject {
/**
* JSONObject.NULL is equivalent to the value that JavaScript calls null,
* whilst Java's null is equivalent to the value that JavaScript calls
* undefined.
*/
protected static final class Null {
/**
* A Null object is equal to the null value and to itself.
*
* @param object an object to test for nullness
* @return true if the object parameter is the JSONObject.NULL object or null
*/
@Override
public boolean equals(Object object) {
return (object == null) || (object == this);
}
/**
* @see Object#hashCode()
*/
@Override
public int hashCode() {
return super.hashCode();
}
/**
* Get the "null" string value.
*
* @return the string "null".
*/
@Override
public String toString() {
return "null";
}
/**
* There is only intended to be a single instance of the NULL object,
* so the clone method returns itself.
*
* @return NULL.
*/
@Override
protected Object clone() {
return this;
}
}
/**
* It is sometimes more convenient and less ambiguous to have a
* 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();
/**
* The map where the JSONObject's properties are kept.
*/
private Map m_map;
/**
* Construct an empty JSONObject.
*/
public JSONObject() {
this(false);
}
/**
* Construct an empty sorted JSONObject.
*
* @param sorted true for sorted, false for none sorted
*/
public JSONObject(boolean sorted) {
if (sorted) {
m_map = new LinkedHashMap();
} else {
m_map = new HashMap();
}
}
/**
* 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
* @exception JSONException if a value is a non-finite number
*/
public JSONObject(JSONObject jo, String[] names)
throws JSONException {
this();
for (int i = 0; i < names.length; i += 1) {
putOpt(names[i], jo.opt(names[i]));
}
}
/**
* 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
*/
public JSONObject(JSONTokener x)
throws JSONException {
this(x, false);
}
/**
* Construct a JSONObject from a JSONTokener, optionally sorted.
*
* @param x a JSONTokener object containing the source string
* @param sorted true for sorted, false for none sorted
* @throws JSONException if there is a syntax error in the source string
*/
public JSONObject(JSONTokener x, boolean sorted)
throws JSONException {
this(sorted);
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 ':'. We will also tolerate '=' or '=>'.
*/
c = x.nextClean();
if (c == '=') {
if (x.next() != '>') {
x.back();
}
} else if (c != ':') {
throw x.syntaxError("Expected a ':' after a key");
}
put(key, x.nextValue());
/*
* Pairs are separated by ','. We will also tolerate ';'.
*/
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(Map map) {
m_map = (map == null) ? new HashMap() : map;
}
/**
* Construct a JSONObject from a Map.
*
* Note: Use this constructor when the map contains <key,bean>.
*
* @param map a map with Key-Bean data
* @param includeSuperClass tell whether to include the super class properties.
*/
public JSONObject(Map map, boolean includeSuperClass) {
m_map = new HashMap();
if (map != null) {
for (Iterator> i = map.entrySet().iterator(); i.hasNext();) {
Map.Entry e = i.next();
m_map.put(e.getKey(), new JSONObject(e.getValue(), includeSuperClass));
}
}
}
/**
* 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(Object bean) {
this();
populateInternalMap(bean, false);
}
/**
* Construct JSONObject from the given bean.
*
* This will also create JSONObject for all internal object (List, Map, Inner Objects) of the provided bean.
*
* @see #JSONObject(Object bean) also.
*
* @param bean an object that has getter methods that should be used to make a JSONObject
* @param includeSuperClass tell whether to include the super class properties.
*/
public JSONObject(Object bean, boolean includeSuperClass) {
this();
populateInternalMap(bean, includeSuperClass);
}
/**
* 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 {
Field field = c.getField(name);
Object value = field.get(object);
this.put(name, value);
} catch (Exception e) {
/* forget about it */
}
}
}
/**
* 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
*/
public JSONObject(String source)
throws JSONException {
this(source, false);
}
/**
* Construct a JSONObject from a source JSON text string, optionally sorted.
*
* This is the most commonly used JSONObject constructor.
*
* @param source a string beginning
* @param sorted true for sorted, false for none sorted
* with {
(left brace) and ending
* with }
(right brace)
* @exception JSONException if there is a syntax error in the source string
*/
public JSONObject(String source, boolean sorted)
throws JSONException {
this(new JSONTokener(source), sorted);
}
/**
* 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 s = Double.toString(d);
if ((s.indexOf('.') > 0) && (s.indexOf('e') < 0) && (s.indexOf('E') < 0)) {
while (s.endsWith("0")) {
s = s.substring(0, s.length() - 1);
}
if (s.endsWith(".")) {
s = s.substring(0, s.length() - 1);
}
}
return s;
}
/**
* Get an array of field names from a JSONObject.
*
* @param jo the 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 i = jo.keys();
String[] names = new String[length];
int j = 0;
while (i.hasNext()) {
names[j] = i.next();
j += 1;
}
return names;
}
/**
* Get an array of field names from an Object.
*
* @param object the object
* @return an array of field names, or null if there are no names
*/
public static String[] getNames(Object object) {
if (object == null) {
return null;
}
Class> klass = object.getClass();
Field[] fields = klass.getFields();
int length = fields.length;
if (length == 0) {
return null;
}
String[] names = new String[length];
for (int i = 0; i < length; i += 1) {
names[i] = fields[i].getName();
}
return names;
}
/**
* Produce a string from a Number.
*
* @param n a Number
* @return a String
* @throws JSONException if n is a non-finite number
*/
public static String numberToString(Number n) throws JSONException {
if (n == null) {
throw new JSONException("Null pointer");
}
testValidity(n);
// Shave off trailing zeros and decimal point, if possible.
String s = n.toString();
if ((s.indexOf('.') > 0) && (s.indexOf('e') < 0) && (s.indexOf('E') < 0)) {
while (s.endsWith("0")) {
s = s.substring(0, s.length() - 1);
}
if (s.endsWith(".")) {
s = s.substring(0, s.length() - 1);
}
}
return s;
}
/**
* Produce a string in double quotes with backslash sequences in all the
* right places.
*
* A backslash will be inserted, 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) {
if ((string == null) || (string.length() == 0)) {
return "\"\"";
}
char b;
char c = 0;
int i;
int len = string.length();
StringBuffer sb = new StringBuffer(len + 4);
String t;
sb.append('"');
for (i = 0; i < len; i += 1) {
b = c;
c = string.charAt(i);
switch (c) {
case '\\':
case '"':
sb.append('\\');
sb.append(c);
break;
case '/':
if (b == '<') {
sb.append('\\');
}
sb.append(c);
break;
case '\b':
sb.append("\\b");
break;
case '\t':
sb.append("\\t");
break;
case '\n':
sb.append("\\n");
break;
case '\f':
sb.append("\\f");
break;
case '\r':
sb.append("\\r");
break;
default:
if ((c == '\'')
|| (c < ' ')
|| ((c >= '\u0080') && (c < '\u00a0'))
|| ((c >= '\u2000') && (c < '\u2100'))) {
t = "000" + Integer.toHexString(c);
sb.append("\\u" + t.substring(t.length() - 4));
} else {
sb.append(c);
}
}
}
sb.append('"');
return sb.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
*/
@SuppressWarnings("unchecked")
public static String valueToString(Object value) throws JSONException {
if ((value == null) || value.equals(null)) {
return "null";
}
if (value instanceof I_JSONString) {
Object o;
try {
o = ((I_JSONString)value).toJSONString();
} catch (Exception e) {
throw new JSONException(e);
}
if (o instanceof String) {
return (String)o;
}
throw new JSONException("Bad value from toJSONString: " + o);
}
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)value).toString();
}
if (value instanceof Collection) {
return new JSONArray((Collection