1
0
Fork 0
mirror of https://github.com/ethauvin/JSON-java.git synced 2025-06-17 07:50:52 -07:00

Revert "reduces the use of unnecessary exceptions"

This reverts commit 7627d40d10.
This commit is contained in:
Nils Faupel 2016-07-19 19:00:42 +02:00
parent 7627d40d10
commit abf2963bbe
2 changed files with 214 additions and 334 deletions

View file

@ -72,13 +72,13 @@ import java.util.Map;
* <li>Strings do not need to be quoted at all if they do not begin with a quote * <li>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 * or single quote, and if they do not contain leading or trailing spaces, and
* if they do not contain any of these characters: * if they do not contain any of these characters:
* <code>{ } [ ] / \ : , #</code> and if they do not look like numbers and if * <code>{ } [ ] / \ : , #</code> and if they do not look like numbers and
* they are not the reserved words <code>true</code>, <code>false</code>, or * if they are not the reserved words <code>true</code>, <code>false</code>, or
* <code>null</code>.</li> * <code>null</code>.</li>
* </ul> * </ul>
* *
* @author JSON.org * @author JSON.org
* @version 2016-07-08 * @version 2016-05-20
*/ */
public class JSONArray implements Iterable<Object> { public class JSONArray implements Iterable<Object> {
@ -156,9 +156,9 @@ public class JSONArray implements Iterable<Object> {
public JSONArray(Collection<?> collection) { public JSONArray(Collection<?> collection) {
this.myArrayList = new ArrayList<Object>(); this.myArrayList = new ArrayList<Object>();
if (collection != null) { if (collection != null) {
for (Object o : collection) { for (Object o: collection){
this.myArrayList.add(JSONObject.wrap(o)); this.myArrayList.add(JSONObject.wrap(o));
} }
} }
} }
@ -241,39 +241,34 @@ public class JSONArray implements Iterable<Object> {
public double getDouble(int index) throws JSONException { public double getDouble(int index) throws JSONException {
Object object = this.get(index); Object object = this.get(index);
try { try {
if (object instanceof Number) { return object instanceof Number ? ((Number) object).doubleValue()
return ((Number) object).doubleValue(); : Double.parseDouble((String) object);
} else if (object instanceof String) {
return Double.parseDouble((String) object);
}
} catch (Exception e) { } catch (Exception e) {
throw new JSONException("JSONArray[" + index + "] is not a number.");
} }
throw new JSONException("JSONArray[" + index + "] is not a number.");
} }
/** /**
* Get the enum value associated with an index. * Get the enum value associated with an index.
* *
* @param clazz * @param clazz
* The type of enum to retrieve. * The type of enum to retrieve.
* @param index * @param index
* The index must be between 0 and length() - 1. * The index must be between 0 and length() - 1.
* @return The enum value at the index location * @return The enum value at the index location
* @throws JSONException * @throws JSONException
* if the key is not found or if the value cannot be converted * if the key is not found or if the value cannot be converted
* to an enum. * to an enum.
*/ */
public <E extends Enum<E>> E getEnum(Class<E> clazz, int index) public <E extends Enum<E>> E getEnum(Class<E> clazz, int index) throws JSONException {
throws JSONException {
E val = optEnum(clazz, index); E val = optEnum(clazz, index);
if (val == null) { if(val==null) {
// JSONException should really take a throwable argument. // JSONException should really take a throwable argument.
// If it did, I would re-implement this with the Enum.valueOf // If it did, I would re-implement this with the Enum.valueOf
// method and place any thrown exception in the JSONException // method and place any thrown exception in the JSONException
throw new JSONException("JSONObject[" throw new JSONException("JSONObject[" + JSONObject.quote(Integer.toString(index))
+ JSONObject.quote(Integer.toString(index)) + "] is not an enum of type " + JSONObject.quote(clazz.getSimpleName())
+ "] is not an enum of type " + ".");
+ JSONObject.quote(clazz.getSimpleName()) + ".");
} }
return val; return val;
} }
@ -288,13 +283,13 @@ public class JSONArray implements Iterable<Object> {
* If the key is not found or if the value cannot be converted * If the key is not found or if the value cannot be converted
* to a BigDecimal. * to a BigDecimal.
*/ */
public BigDecimal getBigDecimal(int index) throws JSONException { public BigDecimal getBigDecimal (int index) throws JSONException {
Object object = this.get(index); Object object = this.get(index);
try { try {
return new BigDecimal(object.toString()); return new BigDecimal(object.toString());
} catch (Exception e) { } catch (Exception e) {
throw new JSONException("JSONArray[" + index throw new JSONException("JSONArray[" + index +
+ "] could not convert to BigDecimal."); "] could not convert to BigDecimal.");
} }
} }
@ -308,13 +303,13 @@ public class JSONArray implements Iterable<Object> {
* If the key is not found or if the value cannot be converted * If the key is not found or if the value cannot be converted
* to a BigInteger. * to a BigInteger.
*/ */
public BigInteger getBigInteger(int index) throws JSONException { public BigInteger getBigInteger (int index) throws JSONException {
Object object = this.get(index); Object object = this.get(index);
try { try {
return new BigInteger(object.toString()); return new BigInteger(object.toString());
} catch (Exception e) { } catch (Exception e) {
throw new JSONException("JSONArray[" + index throw new JSONException("JSONArray[" + index +
+ "] could not convert to BigInteger."); "] could not convert to BigInteger.");
} }
} }
@ -330,14 +325,11 @@ public class JSONArray implements Iterable<Object> {
public int getInt(int index) throws JSONException { public int getInt(int index) throws JSONException {
Object object = this.get(index); Object object = this.get(index);
try { try {
if (object instanceof Number) { return object instanceof Number ? ((Number) object).intValue()
return ((Number) object).intValue(); : Integer.parseInt((String) object);
} else if (object instanceof String) {
return Integer.parseInt((String) object);
}
} catch (Exception e) { } catch (Exception e) {
throw new JSONException("JSONArray[" + index + "] is not a number.");
} }
throw new JSONException("JSONArray[" + index + "] is not a number.");
} }
/** /**
@ -389,14 +381,11 @@ public class JSONArray implements Iterable<Object> {
public long getLong(int index) throws JSONException { public long getLong(int index) throws JSONException {
Object object = this.get(index); Object object = this.get(index);
try { try {
if (object instanceof Number) { return object instanceof Number ? ((Number) object).longValue()
return ((Number) object).longValue(); : Long.parseLong((String) object);
} else if (object instanceof String) {
return Long.parseLong((String) object);
}
} catch (Exception e) { } catch (Exception e) {
throw new JSONException("JSONArray[" + index + "] is not a number.");
} }
throw new JSONException("JSONArray[" + index + "] is not a number.");
} }
/** /**
@ -497,20 +486,11 @@ public class JSONArray implements Iterable<Object> {
* @return The truth. * @return The truth.
*/ */
public boolean optBoolean(int index, boolean defaultValue) { public boolean optBoolean(int index, boolean defaultValue) {
Object object = this.opt(index); try {
if (JSONObject.NULL.equals(object)) { return this.getBoolean(index);
} catch (Exception e) {
return defaultValue; return defaultValue;
} }
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;
}
return defaultValue;
} }
/** /**
@ -538,19 +518,11 @@ public class JSONArray implements Iterable<Object> {
* @return The value. * @return The value.
*/ */
public double optDouble(int index, double defaultValue) { public double optDouble(int index, double defaultValue) {
Object object = this.opt(index); try {
if (JSONObject.NULL.equals(object)) { return this.getDouble(index);
} catch (Exception e) {
return defaultValue; return defaultValue;
} }
try {
if (object instanceof Number) {
return ((Number) object).doubleValue();
} else if (object instanceof String) {
return Double.parseDouble((String) object);
}
} catch (Exception e) {
}
return defaultValue;
} }
/** /**
@ -578,24 +550,16 @@ public class JSONArray implements Iterable<Object> {
* @return The value. * @return The value.
*/ */
public int optInt(int index, int defaultValue) { public int optInt(int index, int defaultValue) {
Object object = this.opt(index); try {
if (JSONObject.NULL.equals(object)) { return this.getInt(index);
} catch (Exception e) {
return defaultValue; return defaultValue;
} }
try {
if (object instanceof Number) {
return ((Number) object).intValue();
} else if (object instanceof String) {
return Integer.parseInt((String) object);
}
} catch (Exception e) {
}
return defaultValue;
} }
/** /**
* Get the enum value associated with a key. * Get the enum value associated with a key.
* *
* @param clazz * @param clazz
* The type of enum to retrieve. * The type of enum to retrieve.
* @param index * @param index
@ -608,18 +572,17 @@ public class JSONArray implements Iterable<Object> {
/** /**
* Get the enum value associated with a key. * Get the enum value associated with a key.
* *
* @param clazz * @param clazz
* The type of enum to retrieve. * The type of enum to retrieve.
* @param index * @param index
* The index must be between 0 and length() - 1. * The index must be between 0 and length() - 1.
* @param defaultValue * @param defaultValue
* The default in case the value is not found * The default in case the value is not found
* @return The enum value at the index location or defaultValue if the value * @return The enum value at the index location or defaultValue if
* is not found or cannot be assigned to clazz * the value is not found or cannot be assigned to clazz
*/ */
public <E extends Enum<E>> E optEnum(Class<E> clazz, int index, public <E extends Enum<E>> E optEnum(Class<E> clazz, int index, E defaultValue) {
E defaultValue) {
try { try {
Object val = this.opt(index); Object val = this.opt(index);
if (JSONObject.NULL.equals(val)) { if (JSONObject.NULL.equals(val)) {
@ -639,9 +602,10 @@ public class JSONArray implements Iterable<Object> {
} }
} }
/** /**
* Get the optional BigInteger value associated with an index. The * Get the optional BigInteger value associated with an index. The
* defaultValue is returned if there is no value for the index, or if the * defaultValue is returned if there is no value for the index, or if the
* value is not a number and cannot be converted to a number. * value is not a number and cannot be converted to a number.
* *
* @param index * @param index
@ -651,20 +615,16 @@ public class JSONArray implements Iterable<Object> {
* @return The value. * @return The value.
*/ */
public BigInteger optBigInteger(int index, BigInteger defaultValue) { public BigInteger optBigInteger(int index, BigInteger defaultValue) {
Object object = this.opt(index);
if (JSONObject.NULL.equals(object)) {
return defaultValue;
}
try { try {
return new BigInteger(object.toString()); return this.getBigInteger(index);
} catch (Exception e) { } catch (Exception e) {
return defaultValue; return defaultValue;
} }
} }
/** /**
* Get the optional BigDecimal value associated with an index. The * Get the optional BigDecimal value associated with an index. The
* defaultValue is returned if there is no value for the index, or if the * defaultValue is returned if there is no value for the index, or if the
* value is not a number and cannot be converted to a number. * value is not a number and cannot be converted to a number.
* *
* @param index * @param index
@ -674,12 +634,8 @@ public class JSONArray implements Iterable<Object> {
* @return The value. * @return The value.
*/ */
public BigDecimal optBigDecimal(int index, BigDecimal defaultValue) { public BigDecimal optBigDecimal(int index, BigDecimal defaultValue) {
Object object = this.opt(index);
if (JSONObject.NULL.equals(object)) {
return defaultValue;
}
try { try {
return new BigDecimal(object.toString()); return this.getBigDecimal(index);
} catch (Exception e) { } catch (Exception e) {
return defaultValue; return defaultValue;
} }
@ -737,19 +693,11 @@ public class JSONArray implements Iterable<Object> {
* @return The value. * @return The value.
*/ */
public long optLong(int index, long defaultValue) { public long optLong(int index, long defaultValue) {
Object object = this.opt(index); try {
if (JSONObject.NULL.equals(object)) { return this.getLong(index);
} catch (Exception e) {
return defaultValue; return defaultValue;
} }
try {
if (object instanceof Number) {
return ((Number) object).longValue();
} else if (object instanceof String) {
return Long.parseLong((String) object);
}
} catch (Exception e) {
}
return defaultValue;
} }
/** /**
@ -1011,44 +959,37 @@ public class JSONArray implements Iterable<Object> {
} }
return this; return this;
} }
/** /**
* Creates a JSONPointer using an initialization string and tries to match * Creates a JSONPointer using an intialization string and tries to
* it to an item within this JSONArray. For example, given a JSONArray * match it to an item within this JSONArray. For example, given a
* initialized with this document: * JSONArray initialized with this document:
*
* <pre> * <pre>
* [ * [
* {"b":"c"} * {"b":"c"}
* ] * ]
* </pre> * </pre>
* * and this JSONPointer string:
* and this JSONPointer string:
*
* <pre> * <pre>
* &quot;/0/b&quot; * "/0/b"
* </pre> * </pre>
* Then this method will return the String "c"
* A JSONPointerException may be thrown from code called by this method.
* *
* Then this method will return the String "c" A JSONPointerException may be * @param jsonPointer string that can be used to create a JSONPointer
* 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 * @return the item matched by the JSONPointer, otherwise null
*/ */
public Object query(String jsonPointer) { public Object query(String jsonPointer) {
return new JSONPointer(jsonPointer).queryFrom(this); return new JSONPointer(jsonPointer).queryFrom(this);
} }
/** /**
* Queries and returns a value from this object using {@code jsonPointer}, * Queries and returns a value from this object using {@code jsonPointer}, or
* or returns null if the query fails due to a missing key. * returns null if the query fails due to a missing key.
* *
* @param jsonPointer * @param jsonPointer the string representation of the JSON pointer
* the string representation of the JSON pointer
* @return the queried value or {@code null} * @return the queried value or {@code null}
* @throws IllegalArgumentException * @throws IllegalArgumentException if {@code jsonPointer} has invalid syntax
* if {@code jsonPointer} has invalid syntax
*/ */
public Object optQuery(String jsonPointer) { public Object optQuery(String jsonPointer) {
JSONPointer pointer = new JSONPointer(jsonPointer); JSONPointer pointer = new JSONPointer(jsonPointer);
@ -1068,16 +1009,16 @@ public class JSONArray implements Iterable<Object> {
* was no value. * was no value.
*/ */
public Object remove(int index) { public Object remove(int index) {
return index >= 0 && index < this.length() ? this.myArrayList return index >= 0 && index < this.length()
.remove(index) : null; ? this.myArrayList.remove(index)
: null;
} }
/** /**
* Determine if two JSONArrays are similar. They must contain similar * Determine if two JSONArrays are similar.
* sequences. * They must contain similar sequences.
* *
* @param other * @param other The other JSONArray
* The other JSONArray
* @return true if they are equal * @return true if they are equal
*/ */
public boolean similar(Object other) { public boolean similar(Object other) {
@ -1085,18 +1026,18 @@ public class JSONArray implements Iterable<Object> {
return false; return false;
} }
int len = this.length(); int len = this.length();
if (len != ((JSONArray) other).length()) { if (len != ((JSONArray)other).length()) {
return false; return false;
} }
for (int i = 0; i < len; i += 1) { for (int i = 0; i < len; i += 1) {
Object valueThis = this.get(i); Object valueThis = this.get(i);
Object valueOther = ((JSONArray) other).get(i); Object valueOther = ((JSONArray)other).get(i);
if (valueThis instanceof JSONObject) { if (valueThis instanceof JSONObject) {
if (!((JSONObject) valueThis).similar(valueOther)) { if (!((JSONObject)valueThis).similar(valueOther)) {
return false; return false;
} }
} else if (valueThis instanceof JSONArray) { } else if (valueThis instanceof JSONArray) {
if (!((JSONArray) valueThis).similar(valueOther)) { if (!((JSONArray)valueThis).similar(valueOther)) {
return false; return false;
} }
} else if (!valueThis.equals(valueOther)) { } else if (!valueThis.equals(valueOther)) {
@ -1140,7 +1081,6 @@ public class JSONArray implements Iterable<Object> {
* @return a printable, displayable, transmittable representation of the * @return a printable, displayable, transmittable representation of the
* array. * array.
*/ */
@Override
public String toString() { public String toString() {
try { try {
return this.toString(0); return this.toString(0);
@ -1150,7 +1090,7 @@ public class JSONArray implements Iterable<Object> {
} }
/** /**
* Make a pretty printed JSON text of this JSONArray. Warning: This method * Make a prettyprinted JSON text of this JSONArray. Warning: This method
* assumes that the data structure is acyclical. * assumes that the data structure is acyclical.
* *
* @param indentFactor * @param indentFactor
@ -1234,9 +1174,9 @@ public class JSONArray implements Iterable<Object> {
} }
/** /**
* Returns a java.util.List containing all of the elements in this array. If * Returns a java.util.List containing all of the elements in this array.
* an element in the array is a JSONArray or JSONObject it will also be * If an element in the array is a JSONArray or JSONObject it will also
* converted. * be converted.
* <p> * <p>
* Warning: This method assumes that the data structure is acyclical. * Warning: This method assumes that the data structure is acyclical.
* *

View file

@ -46,29 +46,32 @@ import java.util.Set;
* A JSONObject is an unordered collection of name/value pairs. Its external * 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 * 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 * values, and commas between the values and names. The internal form is an
* object having <code>get</code> and <code>opt</code> methods for accessing the * object having <code>get</code> and <code>opt</code> methods for accessing
* values by name, and <code>put</code> methods for adding or replacing values * the values by name, and <code>put</code> methods for adding or replacing
* by name. The values can be any of these types: <code>Boolean</code>, * values by name. The values can be any of these types: <code>Boolean</code>,
* <code>JSONArray</code>, <code>JSONObject</code>, <code>Number</code>, * <code>JSONArray</code>, <code>JSONObject</code>, <code>Number</code>,
* <code>String</code>, or the <code>JSONObject.NULL</code> object. A JSONObject * <code>String</code>, or the <code>JSONObject.NULL</code> object. A
* constructor can be used to convert an external form JSON text into an * JSONObject constructor can be used to convert an external form JSON text
* internal form whose values can be retrieved with the <code>get</code> and * into an internal form whose values can be retrieved with the
* <code>opt</code> methods, or to convert values into a JSON text using the * <code>get</code> and <code>opt</code> methods, or to convert values into a
* <code>put</code> and <code>toString</code> methods. A <code>get</code> method * JSON text using the <code>put</code> and <code>toString</code> methods. A
* returns a value if one can be found, and throws an exception if one cannot be * <code>get</code> method returns a value if one can be found, and throws an
* found. An <code>opt</code> method returns a default value instead of throwing * exception if one cannot be found. An <code>opt</code> method returns a
* an exception, and so is useful for obtaining optional values. * default value instead of throwing an exception, and so is useful for
* obtaining optional values.
* <p> * <p>
* The generic <code>get()</code> and <code>opt()</code> methods return an * The generic <code>get()</code> and <code>opt()</code> methods return an
* object, which you can cast or query for type. There are also typed * object, which you can cast or query for type. There are also typed
* <code>get</code> and <code>opt</code> methods that do type checking and type * <code>get</code> and <code>opt</code> methods that do type checking and type
* coercion for you. The opt methods differ from the get methods in that they do * coercion for you. The opt methods differ from the get methods in that they
* not throw. Instead, they return a specified value, such as null. * do not throw. Instead, they return a specified value, such as null.
* <p> * <p>
* The <code>put</code> methods add or replace values in an object. For example, * The <code>put</code> methods add or replace values in an object. For
* example,
* *
* <pre> * <pre>
* myString = new JSONObject().put(&quot;JSON&quot;, &quot;Hello, World!&quot;).toString(); * myString = new JSONObject()
* .put(&quot;JSON&quot;, &quot;Hello, World!&quot;).toString();
* </pre> * </pre>
* *
* produces the string <code>{"JSON": "Hello, World"}</code>. * produces the string <code>{"JSON": "Hello, World"}</code>.
@ -81,16 +84,16 @@ import java.util.Set;
* before the closing brace.</li> * before the closing brace.</li>
* <li>Strings may be quoted with <code>'</code>&nbsp;<small>(single * <li>Strings may be quoted with <code>'</code>&nbsp;<small>(single
* quote)</small>.</li> * quote)</small>.</li>
* <li>Strings do not need to be quoted at all if they do not begin with a quote * <li>Strings do not need to be quoted at all if they do not begin with a
* or single quote, and if they do not contain leading or trailing spaces, and * quote or single quote, and if they do not contain leading or trailing
* if they do not contain any of these characters: * spaces, and if they do not contain any of these characters:
* <code>{ } [ ] / \ : , #</code> and if they do not look like numbers and if * <code>{ } [ ] / \ : , #</code> and if they do not look like numbers and
* they are not the reserved words <code>true</code>, <code>false</code>, or * if they are not the reserved words <code>true</code>, <code>false</code>,
* <code>null</code>.</li> * or <code>null</code>.</li>
* </ul> * </ul>
* *
* @author JSON.org * @author JSON.org
* @version 2016-07-08 * @version 2016-05-20
*/ */
public class JSONObject { public class JSONObject {
/** /**
@ -101,8 +104,8 @@ public class JSONObject {
private static final class Null { private static final class Null {
/** /**
* There is only intended to be a single instance of the NULL object, so * There is only intended to be a single instance of the NULL object,
* the clone method returns itself. * so the clone method returns itself.
* *
* @return NULL. * @return NULL.
*/ */
@ -129,7 +132,6 @@ public class JSONObject {
* *
* @return The string "null". * @return The string "null".
*/ */
@Override
public String toString() { public String toString() {
return "null"; return "null";
} }
@ -204,7 +206,7 @@ public class JSONObject {
key = x.nextValue().toString(); key = x.nextValue().toString();
} }
// The key is followed by ':'. // The key is followed by ':'.
c = x.nextClean(); c = x.nextClean();
if (c != ':') { if (c != ':') {
@ -212,7 +214,7 @@ public class JSONObject {
} }
this.putOnce(key, x.nextValue()); this.putOnce(key, x.nextValue());
// Pairs are separated by ','. // Pairs are separated by ','.
switch (x.nextClean()) { switch (x.nextClean()) {
case ';': case ';':
@ -240,7 +242,7 @@ public class JSONObject {
public JSONObject(Map<?, ?> map) { public JSONObject(Map<?, ?> map) {
this.map = new HashMap<String, Object>(); this.map = new HashMap<String, Object>();
if (map != null) { if (map != null) {
for (final Entry<?, ?> e : map.entrySet()) { for (final Entry<?, ?> e : map.entrySet()) {
final Object value = e.getValue(); final Object value = e.getValue();
if (value != null) { if (value != null) {
this.map.put(String.valueOf(e.getKey()), wrap(value)); this.map.put(String.valueOf(e.getKey()), wrap(value));
@ -332,18 +334,16 @@ public class JSONObject {
ResourceBundle bundle = ResourceBundle.getBundle(baseName, locale, ResourceBundle bundle = ResourceBundle.getBundle(baseName, locale,
Thread.currentThread().getContextClassLoader()); Thread.currentThread().getContextClassLoader());
// Iterate through the keys in the bundle. // Iterate through the keys in the bundle.
Enumeration<String> keys = bundle.getKeys(); Enumeration<String> keys = bundle.getKeys();
while (keys.hasMoreElements()) { while (keys.hasMoreElements()) {
Object key = keys.nextElement(); Object key = keys.nextElement();
if (key != null) { if (key != null) {
// Go through the path, ensuring that there is a nested // Go through the path, ensuring that there is a nested JSONObject for each
// JSONObject for each // segment except the last. Add the value using the last segment's name into
// segment except the last. Add the value using the last // the deepest nested JSONObject.
// segment's name into
// the deepest nested JSONObject.
String[] path = ((String) key).split("\\."); String[] path = ((String) key).split("\\.");
int last = path.length - 1; int last = path.length - 1;
@ -438,7 +438,7 @@ public class JSONObject {
return "null"; return "null";
} }
// Shave off trailing zeros and decimal point, if possible. // Shave off trailing zeros and decimal point, if possible.
String string = Double.toString(d); String string = Double.toString(d);
if (string.indexOf('.') > 0 && string.indexOf('e') < 0 if (string.indexOf('.') > 0 && string.indexOf('e') < 0
@ -474,27 +474,26 @@ public class JSONObject {
} }
/** /**
* Get the enum value associated with a key. * Get the enum value associated with a key.
* *
* @param clazz * @param clazz
* The type of enum to retrieve. * The type of enum to retrieve.
* @param key * @param key
* A key string. * A key string.
* @return The enum value associated with the key * @return The enum value associated with the key
* @throws JSONException * @throws JSONException
* if the key is not found or if the value cannot be converted * if the key is not found or if the value cannot be converted
* to an enum. * to an enum.
*/ */
public <E extends Enum<E>> E getEnum(Class<E> clazz, String key) public <E extends Enum<E>> E getEnum(Class<E> clazz, String key) throws JSONException {
throws JSONException {
E val = optEnum(clazz, key); E val = optEnum(clazz, key);
if (val == null) { if(val==null) {
// JSONException should really take a throwable argument. // JSONException should really take a throwable argument.
// If it did, I would re-implement this with the Enum.valueOf // If it did, I would re-implement this with the Enum.valueOf
// method and place any thrown exception in the JSONException // method and place any thrown exception in the JSONException
throw new JSONException("JSONObject[" + quote(key) throw new JSONException("JSONObject[" + quote(key)
+ "] is not an enum of type " + "] is not an enum of type " + quote(clazz.getSimpleName())
+ quote(clazz.getSimpleName()) + "."); + ".");
} }
return val; return val;
} }
@ -531,8 +530,8 @@ public class JSONObject {
* A key string. * A key string.
* @return The numeric value. * @return The numeric value.
* @throws JSONException * @throws JSONException
* if the key is not found or if the value cannot be converted * if the key is not found or if the value cannot
* to BigInteger. * be converted to BigInteger.
*/ */
public BigInteger getBigInteger(String key) throws JSONException { public BigInteger getBigInteger(String key) throws JSONException {
Object object = this.get(key); Object object = this.get(key);
@ -540,7 +539,7 @@ public class JSONObject {
return new BigInteger(object.toString()); return new BigInteger(object.toString());
} catch (Exception e) { } catch (Exception e) {
throw new JSONException("JSONObject[" + quote(key) throw new JSONException("JSONObject[" + quote(key)
+ "] could not be converted to BigInteger.", e); + "] could not be converted to BigInteger.");
} }
} }
@ -551,8 +550,8 @@ public class JSONObject {
* A key string. * A key string.
* @return The numeric value. * @return The numeric value.
* @throws JSONException * @throws JSONException
* if the key is not found or if the value cannot be converted * if the key is not found or if the value
* to BigDecimal. * cannot be converted to BigDecimal.
*/ */
public BigDecimal getBigDecimal(String key) throws JSONException { public BigDecimal getBigDecimal(String key) throws JSONException {
Object object = this.get(key); Object object = this.get(key);
@ -560,7 +559,7 @@ public class JSONObject {
return new BigDecimal(object.toString()); return new BigDecimal(object.toString());
} catch (Exception e) { } catch (Exception e) {
throw new JSONException("JSONObject[" + quote(key) throw new JSONException("JSONObject[" + quote(key)
+ "] could not be converted to BigDecimal.", e); + "] could not be converted to BigDecimal.");
} }
} }
@ -577,15 +576,12 @@ public class JSONObject {
public double getDouble(String key) throws JSONException { public double getDouble(String key) throws JSONException {
Object object = this.get(key); Object object = this.get(key);
try { try {
if (object instanceof Number) { return object instanceof Number ? ((Number) object).doubleValue()
return ((Number) object).doubleValue(); : Double.parseDouble((String) object);
} else if (object instanceof String) {
return Double.parseDouble((String) object);
}
} catch (Exception e) { } catch (Exception e) {
throw new JSONException("JSONObject[" + quote(key)
+ "] is not a number.");
} }
throw new JSONException("JSONObject[" + quote(key)
+ "] is not a number.");
} }
/** /**
@ -601,14 +597,12 @@ public class JSONObject {
public int getInt(String key) throws JSONException { public int getInt(String key) throws JSONException {
Object object = this.get(key); Object object = this.get(key);
try { try {
if (object instanceof Number) { return object instanceof Number ? ((Number) object).intValue()
return ((Number) object).intValue(); : Integer.parseInt((String) object);
} else if (object instanceof String) {
return Integer.parseInt((String) object);
}
} catch (Exception e) { } catch (Exception e) {
throw new JSONException("JSONObject[" + quote(key)
+ "] is not an int.");
} }
throw new JSONException("JSONObject[" + quote(key) + "] is not an int.");
} }
/** /**
@ -660,14 +654,12 @@ public class JSONObject {
public long getLong(String key) throws JSONException { public long getLong(String key) throws JSONException {
Object object = this.get(key); Object object = this.get(key);
try { try {
if (object instanceof Number) { return object instanceof Number ? ((Number) object).longValue()
return ((Number) object).longValue(); : Long.parseLong((String) object);
} else if (object instanceof String) {
return Long.parseLong((String) object);
}
} catch (Exception e) { } catch (Exception e) {
throw new JSONException("JSONObject[" + quote(key)
+ "] is not a long.");
} }
throw new JSONException("JSONObject[" + quote(key) + "] is not a long.");
} }
/** /**
@ -757,9 +749,9 @@ public class JSONObject {
if (value == null) { if (value == null) {
this.put(key, 1); this.put(key, 1);
} else if (value instanceof BigInteger) { } else if (value instanceof BigInteger) {
this.put(key, ((BigInteger) value).add(BigInteger.ONE)); this.put(key, ((BigInteger)value).add(BigInteger.ONE));
} else if (value instanceof BigDecimal) { } else if (value instanceof BigDecimal) {
this.put(key, ((BigDecimal) value).add(BigDecimal.ONE)); this.put(key, ((BigDecimal)value).add(BigDecimal.ONE));
} else if (value instanceof Integer) { } else if (value instanceof Integer) {
this.put(key, (Integer) value + 1); this.put(key, (Integer) value + 1);
} else if (value instanceof Long) { } else if (value instanceof Long) {
@ -784,7 +776,7 @@ public class JSONObject {
* is the JSONObject.NULL object. * is the JSONObject.NULL object.
*/ */
public boolean isNull(String key) { public boolean isNull(String key) {
return NULL.equals(this.opt(key)); return JSONObject.NULL.equals(this.opt(key));
} }
/** /**
@ -845,7 +837,7 @@ public class JSONObject {
} }
testValidity(number); testValidity(number);
// Shave off trailing zeros and decimal point, if possible. // Shave off trailing zeros and decimal point, if possible.
String string = number.toString(); String string = number.toString();
if (string.indexOf('.') > 0 && string.indexOf('e') < 0 if (string.indexOf('.') > 0 && string.indexOf('e') < 0
@ -873,7 +865,7 @@ public class JSONObject {
/** /**
* Get the enum value associated with a key. * Get the enum value associated with a key.
* *
* @param clazz * @param clazz
* The type of enum to retrieve. * The type of enum to retrieve.
* @param key * @param key
@ -886,18 +878,17 @@ public class JSONObject {
/** /**
* Get the enum value associated with a key. * Get the enum value associated with a key.
* *
* @param clazz * @param clazz
* The type of enum to retrieve. * The type of enum to retrieve.
* @param key * @param key
* A key string. * A key string.
* @param defaultValue * @param defaultValue
* The default in case the value is not found * The default in case the value is not found
* @return The enum value associated with the key or defaultValue if the * @return The enum value associated with the key or defaultValue
* value is not found or cannot be assigned to clazz * if the value is not found or cannot be assigned to clazz
*/ */
public <E extends Enum<E>> E optEnum(Class<E> clazz, String key, public <E extends Enum<E>> E optEnum(Class<E> clazz, String key, E defaultValue) {
E defaultValue) {
try { try {
Object val = this.opt(key); Object val = this.opt(key);
if (NULL.equals(val)) { if (NULL.equals(val)) {
@ -941,20 +932,11 @@ public class JSONObject {
* @return The truth. * @return The truth.
*/ */
public boolean optBoolean(String key, boolean defaultValue) { public boolean optBoolean(String key, boolean defaultValue) {
Object object = this.get(key); try {
if (NULL.equals(object)) { return this.getBoolean(key);
} catch (Exception e) {
return defaultValue; return defaultValue;
} }
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;
}
return defaultValue;
} }
/** /**
@ -982,12 +964,8 @@ public class JSONObject {
* @return An object which is the value. * @return An object which is the value.
*/ */
public BigInteger optBigInteger(String key, BigInteger defaultValue) { public BigInteger optBigInteger(String key, BigInteger defaultValue) {
Object object = this.get(key);
if (NULL.equals(object)) {
return defaultValue;
}
try { try {
return new BigInteger(object.toString()); return this.getBigInteger(key);
} catch (Exception e) { } catch (Exception e) {
return defaultValue; return defaultValue;
} }
@ -1005,12 +983,8 @@ public class JSONObject {
* @return An object which is the value. * @return An object which is the value.
*/ */
public BigDecimal optBigDecimal(String key, BigDecimal defaultValue) { public BigDecimal optBigDecimal(String key, BigDecimal defaultValue) {
Object object = this.opt(key);
if (NULL.equals(object)) {
return defaultValue;
}
try { try {
return new BigDecimal(object.toString()); return this.getBigDecimal(key);
} catch (Exception e) { } catch (Exception e) {
return defaultValue; return defaultValue;
} }
@ -1028,19 +1002,11 @@ public class JSONObject {
* @return An object which is the value. * @return An object which is the value.
*/ */
public double optDouble(String key, double defaultValue) { public double optDouble(String key, double defaultValue) {
Object object = this.get(key); try {
if (NULL.equals(object)) { return this.getDouble(key);
} catch (Exception e) {
return defaultValue; return defaultValue;
} }
try {
if (object instanceof Number) {
return ((Number) object).doubleValue();
} else if (object instanceof String) {
return Double.parseDouble((String) object);
}
} catch (Exception e) {
}
return defaultValue;
} }
/** /**
@ -1068,19 +1034,11 @@ public class JSONObject {
* @return An object which is the value. * @return An object which is the value.
*/ */
public int optInt(String key, int defaultValue) { public int optInt(String key, int defaultValue) {
Object object = this.get(key); try {
if (NULL.equals(object)) { return this.getInt(key);
} catch (Exception e) {
return defaultValue; return defaultValue;
} }
try {
if (object instanceof Number) {
return ((Number) object).intValue();
} else if (object instanceof String) {
return Integer.parseInt((String) object);
}
} catch (Exception e) {
}
return defaultValue;
} }
/** /**
@ -1134,19 +1092,11 @@ public class JSONObject {
* @return An object which is the value. * @return An object which is the value.
*/ */
public long optLong(String key, long defaultValue) { public long optLong(String key, long defaultValue) {
Object object = this.get(key); try {
if (NULL.equals(object)) { return this.getLong(key);
} catch (Exception e) {
return defaultValue; return defaultValue;
} }
try {
if (object instanceof Number) {
return ((Number) object).longValue();
} else if (object instanceof String) {
return Long.parseLong((String) object);
}
} catch (Exception e) {
}
return defaultValue;
} }
/** /**
@ -1180,7 +1130,7 @@ public class JSONObject {
private void populateMap(Object bean) { private void populateMap(Object bean) {
Class<?> klass = bean.getClass(); Class<?> klass = bean.getClass();
// If klass is a System class then set includeSuperClass to false. // If klass is a System class then set includeSuperClass to false.
boolean includeSuperClass = klass.getClassLoader() != null; boolean includeSuperClass = klass.getClassLoader() != null;
@ -1351,10 +1301,8 @@ public class JSONObject {
* are both non-null, and only if there is not already a member with that * are both non-null, and only if there is not already a member with that
* name. * name.
* *
* @param key * @param key string
* string * @param value object
* @param value
* object
* @return this. * @return this.
* @throws JSONException * @throws JSONException
* if the key is a duplicate * if the key is a duplicate
@ -1391,42 +1339,35 @@ public class JSONObject {
} }
/** /**
* Creates a JSONPointer using an initialization string and tries to match * Creates a JSONPointer using an intialization string and tries to
* it to an item within this JSONObject. For example, given a JSONObject * match it to an item within this JSONObject. For example, given a
* initialized with this document: * JSONObject initialized with this document:
*
* <pre> * <pre>
* { * {
* "a":{"b":"c"} * "a":{"b":"c"}
* } * }
* </pre> * </pre>
* * and this JSONPointer string:
* and this JSONPointer string:
*
* <pre> * <pre>
* &quot;/a/b&quot; * "/a/b"
* </pre> * </pre>
* * Then this method will return the String "c".
* Then this method will return the String "c". A JSONPointerException may * A JSONPointerException may be thrown from code called by this method.
* be thrown from code called by this method. *
* * @param jsonPointer string that can be used to create a JSONPointer
* @param jsonPointer
* string that can be used to create a JSONPointer
* @return the item matched by the JSONPointer, otherwise null * @return the item matched by the JSONPointer, otherwise null
*/ */
public Object query(String jsonPointer) { public Object query(String jsonPointer) {
return new JSONPointer(jsonPointer).queryFrom(this); return new JSONPointer(jsonPointer).queryFrom(this);
} }
/** /**
* Queries and returns a value from this object using {@code jsonPointer}, * Queries and returns a value from this object using {@code jsonPointer}, or
* or returns null if the query fails due to a missing key. * returns null if the query fails due to a missing key.
* *
* @param jsonPointer * @param jsonPointer the string representation of the JSON pointer
* the string representation of the JSON pointer
* @return the queried value or {@code null} * @return the queried value or {@code null}
* @throws IllegalArgumentException * @throws IllegalArgumentException if {@code jsonPointer} has invalid syntax
* if {@code jsonPointer} has invalid syntax
*/ */
public Object optQuery(String jsonPointer) { public Object optQuery(String jsonPointer) {
JSONPointer pointer = new JSONPointer(jsonPointer); JSONPointer pointer = new JSONPointer(jsonPointer);
@ -1531,11 +1472,11 @@ public class JSONObject {
} }
/** /**
* Determine if two JSONObjects are similar. They must contain the same set * Determine if two JSONObjects are similar.
* of names which must be associated with similar values. * They must contain the same set of names which must be associated with
* similar values.
* *
* @param other * @param other The other JSONObject
* The other JSONObject
* @return true if they are equal * @return true if they are equal
*/ */
public boolean similar(Object other) { public boolean similar(Object other) {
@ -1544,20 +1485,20 @@ public class JSONObject {
return false; return false;
} }
Set<String> set = this.keySet(); Set<String> set = this.keySet();
if (!set.equals(((JSONObject) other).keySet())) { if (!set.equals(((JSONObject)other).keySet())) {
return false; return false;
} }
Iterator<String> iterator = set.iterator(); Iterator<String> iterator = set.iterator();
while (iterator.hasNext()) { while (iterator.hasNext()) {
String name = iterator.next(); String name = iterator.next();
Object valueThis = this.get(name); Object valueThis = this.get(name);
Object valueOther = ((JSONObject) other).get(name); Object valueOther = ((JSONObject)other).get(name);
if (valueThis instanceof JSONObject) { if (valueThis instanceof JSONObject) {
if (!((JSONObject) valueThis).similar(valueOther)) { if (!((JSONObject)valueThis).similar(valueOther)) {
return false; return false;
} }
} else if (valueThis instanceof JSONArray) { } else if (valueThis instanceof JSONArray) {
if (!((JSONArray) valueThis).similar(valueOther)) { if (!((JSONArray)valueThis).similar(valueOther)) {
return false; return false;
} }
} else if (!valueThis.equals(valueOther)) { } else if (!valueThis.equals(valueOther)) {
@ -1601,7 +1542,8 @@ public class JSONObject {
if ((initial >= '0' && initial <= '9') || initial == '-') { if ((initial >= '0' && initial <= '9') || initial == '-') {
try { try {
if (string.indexOf('.') > -1 || string.indexOf('e') > -1 if (string.indexOf('.') > -1 || string.indexOf('e') > -1
|| string.indexOf('E') > -1 || "-0".equals(string)) { || string.indexOf('E') > -1
|| "-0".equals(string)) {
Double d = Double.valueOf(string); Double d = Double.valueOf(string);
if (!d.isInfinite() && !d.isNaN()) { if (!d.isInfinite() && !d.isNaN()) {
return d; return d;
@ -1679,7 +1621,6 @@ public class JSONObject {
* brace)</small> and ending with <code>}</code>&nbsp;<small>(right * brace)</small> and ending with <code>}</code>&nbsp;<small>(right
* brace)</small>. * brace)</small>.
*/ */
@Override
public String toString() { public String toString() {
try { try {
return this.toString(0); return this.toString(0);
@ -1923,8 +1864,7 @@ public class JSONObject {
if (indentFactor > 0) { if (indentFactor > 0) {
writer.write(' '); writer.write(' ');
} }
writeValue(writer, this.map.get(key), indentFactor, writeValue(writer, this.map.get(key), indentFactor, newindent);
newindent);
commanate = true; commanate = true;
} }
if (indentFactor > 0) { if (indentFactor > 0) {
@ -1940,13 +1880,13 @@ public class JSONObject {
} }
/** /**
* Returns a java.util.Map containing all of the entries in this object. If * Returns a java.util.Map containing all of the entrys in this object.
* an entry in the object is a JSONArray or JSONObject it will also be * If an entry in the object is a JSONArray or JSONObject it will also
* converted. * be converted.
* <p> * <p>
* Warning: This method assumes that the data structure is acyclical. * Warning: This method assumes that the data structure is acyclical.
* *
* @return a java.util.Map containing the entries of this object * @return a java.util.Map containing the entrys of this object
*/ */
public Map<String, Object> toMap() { public Map<String, Object> toMap() {
Map<String, Object> results = new HashMap<String, Object>(); Map<String, Object> results = new HashMap<String, Object>();