/*-
* ============LICENSE_START==========================================
* OPENECOMP - DCAE
* ===================================================================
* Copyright (c) 2017 AT&T Intellectual Property. All rights reserved.
* ===================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ============LICENSE_END============================================
*/
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.Writer;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
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.TreeSet;
// Changed to make it ordered collection.
/**
* 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 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:
*
,
(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
.=
or =>
as well as
* by :
.;
(semicolon) as
* well as by ,
(comma).0-
(octal) or
* 0x-
(hex) prefix.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 LinkedHashMap"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 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.
*
* @param bean An object that has getter methods that should be used
* to make a JSONObject.
* @param includeSuperClass If true, include the super class properties.
*/
public JSONObject(Object bean, boolean includeSuperClass) {
this();
populateInternalMap(bean, includeSuperClass);
}
private void populateInternalMap(Object bean, boolean includeSuperClass){
Class extends Object> klass = bean.getClass();
/* If klass.getSuperClass is System class then force includeSuperClass to false. */
if (klass.getClassLoader() == null) {
includeSuperClass = false;
}
Method[] methods = (includeSuperClass) ?
klass.getMethods() : klass.getDeclaredMethods();
for (int i = 0; i < methods.length; i += 1) {
try {
Method method = methods[i];
if (Modifier.isPublic(method.getModifiers())) {
String name = method.getName();
String k = "";
if (name.startsWith("get")) {
k = name.substring(3);
} else if (name.startsWith("is")) {
k = name.substring(2);
}
if (k.length() > 0 &&
Character.isUpperCase(k.charAt(0)) &&
method.getParameterTypes().length == 0) {
if (k.length() == 1) {
k = k.toLowerCase();
} else if (!Character.isUpperCase(k.charAt(1))) {
k = k.substring(0, 1).toLowerCase() +
k.substring(1);
}
Object result = method.invoke(bean, (Object[])null);
if (result == null) {
map.put(k, NULL);
} else if (result.getClass().isArray()) {
map.put(k, new JSONArray(result, includeSuperClass));
} else if (result instanceof Collection) { // List or Set
map.put(k, new JSONArray((Collection>)result, includeSuperClass));
} else if (result instanceof Map) {
map.put(k, new JSONObject((Map, ?>)result, includeSuperClass));
} else if (isStandardProperty(result.getClass())) { // Primitives, String and Wrapper
map.put(k, result);
} else {
if (result.getClass().getPackage().getName().startsWith("java") ||
result.getClass().getClassLoader() == null) {
map.put(k, result.toString());
} else { // User defined Objects
map.put(k, new JSONObject(result, includeSuperClass));
}
}
}
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
static boolean isStandardProperty(Class extends Object> clazz) {
return clazz.isPrimitive() ||
clazz.isAssignableFrom(Byte.class) ||
clazz.isAssignableFrom(Short.class) ||
clazz.isAssignableFrom(Integer.class) ||
clazz.isAssignableFrom(Long.class) ||
clazz.isAssignableFrom(Float.class) ||
clazz.isAssignableFrom(Double.class) ||
clazz.isAssignableFrom(Character.class) ||
clazz.isAssignableFrom(String.class) ||
clazz.isAssignableFrom(Boolean.class);
}
/**
* 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 {
putOpt(name, c.getField(name).get(object));
} 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 or a duplicated key.
*/
public JSONObject(String source) throws JSONException {
this(new JSONTokener(source));
}
/**
* 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.
* @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 o = opt(key);
if (o == null) {
put(key, value instanceof JSONArray ?
new JSONArray().put(value) :
value);
} else if (o instanceof JSONArray) {
((JSONArray)o).put(value);
} else {
put(key, new JSONArray().put(o).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 o = opt(key);
if (o == null) {
put(key, new JSONArray().put(value));
} else if (o instanceof JSONArray) {
put(key, ((JSONArray)o).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.
*/
static public 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 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 {
Object o = opt(key);
if (o == null) {
throw new JSONException("JSONObject[" + quote(key) +
"] not found.");
}
return o;
}
/**
* 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 o = get(key);
if (o.equals(Boolean.FALSE) ||
(o instanceof String &&
((String)o).equalsIgnoreCase("false"))) {
return false;
} else if (o.equals(Boolean.TRUE) ||
(o instanceof String &&
((String)o).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 o = get(key);
try {
return o instanceof Number ?
((Number)o).doubleValue() :
Double.valueOf((String)o).doubleValue();
} catch (Exception e) {
throw new JSONException("JSONObject[" + quote(key) +
"] is not a number.");
}
}
/**
* Get the int value associated with a key. If the number value is too
* large for an int, it will be clipped.
*
* @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 o = get(key);
return o instanceof Number ?
((Number)o).intValue() : (int)getDouble(key);
}
/**
* 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 o = get(key);
if (o instanceof JSONArray) {
return (JSONArray)o;
}
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 o = get(key);
if (o instanceof JSONObject) {
return (JSONObject)o;
}
throw new JSONException("JSONObject[" + quote(key) +
"] is not a JSONObject.");
}
/**
* Get the long value associated with a key. If the number value is too
* long for a long, it will be clipped.
*
* @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 o = get(key);
return o instanceof Number ?
((Number)o).longValue() : (long)getDouble(key);
}
/**
* 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
* 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
* Warning: This method assumes that the data structure is acyclical.
* @param indentFactor The number of spaces to add to each level of
* indentation.
* @param indent The indentation of the top level.
* @return a printable, displayable, transmittable
* representation of the object, beginning
* with
* 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.
* @param value The value to be serialized.
* @param indentFactor The number of spaces to add to each level of
* indentation.
* @param indent The indentation of the top level.
* @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 {
try {
boolean b = false;
Iterator{
(left brace) and ending
* with }
(right brace).
*/
@Override
public String toString() {
try {
Iterator{
(left brace) and ending
* with }
(right brace).
* @throws JSONException If the object contains an invalid number.
*/
public String toString(int indentFactor) throws JSONException {
return toString(indentFactor, 0);
}
/**
* Make a prettyprinted JSON text of this JSONObject.
* {
(left brace) and ending
* with }
(right brace).
* @throws JSONException If the object contains an invalid number.
*/
String toString(int indentFactor, int indent) throws JSONException {
int j;
int n = length();
if (n == 0) {
return "{}";
}
// Iterator{
(left brace) and ending
* with }
(right brace).
* @throws JSONException If the value is or contains an invalid number.
*/
static String valueToString(Object value) throws JSONException {
if (value == null || value.equals(null)) {
return "null";
}
if (value instanceof JSONString) {
Object o;
try {
o = ((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>)value).toString();
}
if (value.getClass().isArray()) {
return new JSONArray(value).toString();
}
return quote(value.toString());
}
/**
* Make a prettyprinted JSON text of an object value.
* {
(left brace) and ending
* with }
(right brace).
* @throws JSONException If the object contains an invalid number.
*/
public static String valueToString(Object value, int indentFactor, int indent)
throws JSONException {
if (value == null || value.equals(null)) {
return "null";
}
try {
if (value instanceof JSONString) {
Object o = ((JSONString)value).toJSONString();
if (o instanceof String) {
return (String)o;
}
}
} catch (Exception e) {
/* forget about it */
}
if (value instanceof Number) {
return numberToString((Number) value);
}
if (value instanceof Boolean) {
return value.toString();
}
if (value instanceof JSONObject) {
return ((JSONObject)value).toString(indentFactor, indent);
}
if (value instanceof JSONArray) {
return ((JSONArray)value).toString(indentFactor, indent);
}
if (value instanceof Map) {
return new JSONObject((Map, ?>)value).toString(indentFactor, indent);
}
if (value instanceof Collection) {
return new JSONArray((Collection>)value).toString(indentFactor, indent);
}
if (value.getClass().isArray()) {
return new JSONArray(value).toString(indentFactor, indent);
}
return quote(value.toString());
}
/**
* Write the contents of the JSONObject as JSON text to a writer.
* For compactness, no whitespace is added.
*