mirror of
https://github.com/stleary/JSON-java.git
synced 2026-01-25 00:00:38 -05:00
Compare commits
34 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5b845f28cf | ||
|
|
00e0e6c0a2 | ||
|
|
d5b278539e | ||
|
|
12bbe8cd9a | ||
|
|
09dddb826e | ||
|
|
19e9bb6c07 | ||
|
|
fea0aca2ab | ||
|
|
1a811f1ada | ||
|
|
34cfe6df14 | ||
|
|
71c6dd1e34 | ||
|
|
30c1bd16ba | ||
|
|
bc347d2c19 | ||
|
|
a63fa03062 | ||
|
|
16225efbdd | ||
|
|
b8a3342eb1 | ||
|
|
37f5bf28e9 | ||
|
|
7a17ae0b3e | ||
|
|
7cad4c3b26 | ||
|
|
05074386d3 | ||
|
|
a490ebdb78 | ||
|
|
3c1535d724 | ||
|
|
a6284df9c7 | ||
|
|
bfb300835f | ||
|
|
ca9df04539 | ||
|
|
06e9ad280f | ||
|
|
2362c930d1 | ||
|
|
2a6b5bacc5 | ||
|
|
a509a28ed4 | ||
|
|
1c1ef5b211 | ||
|
|
74b9a60f98 | ||
|
|
b63b976acb | ||
|
|
97e180444d | ||
|
|
d402a99fd8 | ||
|
|
7073bc8c47 |
3
.gitignore
vendored
3
.gitignore
vendored
@@ -1,3 +1,6 @@
|
||||
# ignore eclipse project files
|
||||
.project
|
||||
.classpath
|
||||
# ignore Intellij Idea project files
|
||||
.idea
|
||||
*.iml
|
||||
|
||||
365
JSONArray.java
365
JSONArray.java
@@ -36,6 +36,7 @@ import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
|
||||
/**
|
||||
* A JSONArray is an ordered sequence of values. Its external text form is a
|
||||
* string wrapped in square brackets with commas separating the values. The
|
||||
@@ -179,10 +180,16 @@ public class JSONArray implements Iterable<Object> {
|
||||
}
|
||||
|
||||
/**
|
||||
* Construct a JSONArray from an array
|
||||
* Construct a JSONArray from an array.
|
||||
*
|
||||
* @param array
|
||||
* Array. If the parameter passed is null, or not an array, an
|
||||
* exception will be thrown.
|
||||
*
|
||||
* @throws JSONException
|
||||
* If not an array.
|
||||
* If not an array or if an array value is non-finite number.
|
||||
* @throws NullPointerException
|
||||
* Thrown if the array parameter is null.
|
||||
*/
|
||||
public JSONArray(Object array) throws JSONException {
|
||||
this();
|
||||
@@ -256,13 +263,7 @@ public class JSONArray implements Iterable<Object> {
|
||||
* to a number.
|
||||
*/
|
||||
public double getDouble(int index) throws JSONException {
|
||||
Object object = this.get(index);
|
||||
try {
|
||||
return object instanceof Number ? ((Number) object).doubleValue()
|
||||
: Double.parseDouble((String) object);
|
||||
} catch (Exception e) {
|
||||
throw new JSONException("JSONArray[" + index + "] is not a number.", e);
|
||||
}
|
||||
return this.getNumber(index).doubleValue();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -276,14 +277,7 @@ public class JSONArray implements Iterable<Object> {
|
||||
* object and cannot be converted to a number.
|
||||
*/
|
||||
public float getFloat(int index) throws JSONException {
|
||||
Object object = this.get(index);
|
||||
try {
|
||||
return object instanceof Number ? ((Number) object).floatValue()
|
||||
: Float.parseFloat(object.toString());
|
||||
} catch (Exception e) {
|
||||
throw new JSONException("JSONArray[" + index
|
||||
+ "] is not a number.", e);
|
||||
}
|
||||
return this.getNumber(index).floatValue();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -309,17 +303,19 @@ public class JSONArray implements Iterable<Object> {
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the enum value associated with an index.
|
||||
*
|
||||
* @param clazz
|
||||
* The type of enum to retrieve.
|
||||
* @param index
|
||||
* The index must be between 0 and length() - 1.
|
||||
* @return The enum value at the index location
|
||||
* @throws JSONException
|
||||
* if the key is not found or if the value cannot be converted
|
||||
* to an enum.
|
||||
*/
|
||||
* Get the enum value associated with an index.
|
||||
*
|
||||
* @param <E>
|
||||
* Enum Type
|
||||
* @param clazz
|
||||
* The type of enum to retrieve.
|
||||
* @param index
|
||||
* The index must be between 0 and length() - 1.
|
||||
* @return The enum value at the index location
|
||||
* @throws JSONException
|
||||
* if the key is not found or if the value cannot be converted
|
||||
* to an enum.
|
||||
*/
|
||||
public <E extends Enum<E>> E getEnum(Class<E> clazz, int index) throws JSONException {
|
||||
E val = optEnum(clazz, index);
|
||||
if(val==null) {
|
||||
@@ -333,7 +329,10 @@ public class JSONArray implements Iterable<Object> {
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the BigDecimal value associated with an index.
|
||||
* Get the BigDecimal value associated with an index. If the value is float
|
||||
* or double, the the {@link BigDecimal#BigDecimal(double)} constructor
|
||||
* will be used. See notes on the constructor for conversion issues that
|
||||
* may arise.
|
||||
*
|
||||
* @param index
|
||||
* The index must be between 0 and length() - 1.
|
||||
@@ -344,12 +343,12 @@ public class JSONArray implements Iterable<Object> {
|
||||
*/
|
||||
public BigDecimal getBigDecimal (int index) throws JSONException {
|
||||
Object object = this.get(index);
|
||||
try {
|
||||
return new BigDecimal(object.toString());
|
||||
} catch (Exception e) {
|
||||
BigDecimal val = JSONObject.objectToBigDecimal(object, null);
|
||||
if(val == null) {
|
||||
throw new JSONException("JSONArray[" + index +
|
||||
"] could not convert to BigDecimal.", e);
|
||||
"] could not convert to BigDecimal ("+ object + ").");
|
||||
}
|
||||
return val;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -364,12 +363,12 @@ public class JSONArray implements Iterable<Object> {
|
||||
*/
|
||||
public BigInteger getBigInteger (int index) throws JSONException {
|
||||
Object object = this.get(index);
|
||||
try {
|
||||
return new BigInteger(object.toString());
|
||||
} catch (Exception e) {
|
||||
BigInteger val = JSONObject.objectToBigInteger(object, null);
|
||||
if(val == null) {
|
||||
throw new JSONException("JSONArray[" + index +
|
||||
"] could not convert to BigInteger.", e);
|
||||
"] could not convert to BigDecimal ("+ object + ").");
|
||||
}
|
||||
return val;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -382,13 +381,7 @@ public class JSONArray implements Iterable<Object> {
|
||||
* If the key is not found or if the value is not a number.
|
||||
*/
|
||||
public int getInt(int index) throws JSONException {
|
||||
Object object = this.get(index);
|
||||
try {
|
||||
return object instanceof Number ? ((Number) object).intValue()
|
||||
: Integer.parseInt((String) object);
|
||||
} catch (Exception e) {
|
||||
throw new JSONException("JSONArray[" + index + "] is not a number.", e);
|
||||
}
|
||||
return this.getNumber(index).intValue();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -438,13 +431,7 @@ public class JSONArray implements Iterable<Object> {
|
||||
* to a number.
|
||||
*/
|
||||
public long getLong(int index) throws JSONException {
|
||||
Object object = this.get(index);
|
||||
try {
|
||||
return object instanceof Number ? ((Number) object).longValue()
|
||||
: Long.parseLong((String) object);
|
||||
} catch (Exception e) {
|
||||
throw new JSONException("JSONArray[" + index + "] is not a number.", e);
|
||||
}
|
||||
return this.getNumber(index).longValue();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -465,11 +452,11 @@ public class JSONArray implements Iterable<Object> {
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine if the value is null.
|
||||
* Determine if the value is <code>null</code>.
|
||||
*
|
||||
* @param index
|
||||
* The index must be between 0 and length() - 1.
|
||||
* @return true if the value at the index is null, or if there is no value.
|
||||
* @return true if the value at the index is <code>null</code>, or if there is no value.
|
||||
*/
|
||||
public boolean isNull(int index) {
|
||||
return JSONObject.NULL.equals(this.opt(index));
|
||||
@@ -488,13 +475,16 @@ public class JSONArray implements Iterable<Object> {
|
||||
*/
|
||||
public String join(String separator) throws JSONException {
|
||||
int len = this.length();
|
||||
StringBuilder sb = new StringBuilder();
|
||||
if (len == 0) {
|
||||
return "";
|
||||
}
|
||||
|
||||
StringBuilder sb = new StringBuilder(
|
||||
JSONObject.valueToString(this.myArrayList.get(0)));
|
||||
|
||||
for (int i = 0; i < len; i += 1) {
|
||||
if (i > 0) {
|
||||
sb.append(separator);
|
||||
}
|
||||
sb.append(JSONObject.valueToString(this.myArrayList.get(i)));
|
||||
for (int i = 1; i < len; i++) {
|
||||
sb.append(separator)
|
||||
.append(JSONObject.valueToString(this.myArrayList.get(i)));
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
@@ -577,21 +567,15 @@ public class JSONArray implements Iterable<Object> {
|
||||
* @return The value.
|
||||
*/
|
||||
public double optDouble(int index, double defaultValue) {
|
||||
Object val = this.opt(index);
|
||||
if (JSONObject.NULL.equals(val)) {
|
||||
final Number val = this.optNumber(index, null);
|
||||
if (val == null) {
|
||||
return defaultValue;
|
||||
}
|
||||
if (val instanceof Number){
|
||||
return ((Number) val).doubleValue();
|
||||
}
|
||||
if (val instanceof String) {
|
||||
try {
|
||||
return Double.parseDouble((String) val);
|
||||
} catch (Exception e) {
|
||||
return defaultValue;
|
||||
}
|
||||
}
|
||||
return defaultValue;
|
||||
final double doubleValue = val.doubleValue();
|
||||
// if (Double.isNaN(doubleValue) || Double.isInfinite(doubleValue)) {
|
||||
// return defaultValue;
|
||||
// }
|
||||
return doubleValue;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -619,21 +603,15 @@ public class JSONArray implements Iterable<Object> {
|
||||
* @return The value.
|
||||
*/
|
||||
public float optFloat(int index, float defaultValue) {
|
||||
Object val = this.opt(index);
|
||||
if (JSONObject.NULL.equals(val)) {
|
||||
final Number val = this.optNumber(index, null);
|
||||
if (val == null) {
|
||||
return defaultValue;
|
||||
}
|
||||
if (val instanceof Number){
|
||||
return ((Number) val).floatValue();
|
||||
}
|
||||
if (val instanceof String) {
|
||||
try {
|
||||
return Float.parseFloat((String) val);
|
||||
} catch (Exception e) {
|
||||
return defaultValue;
|
||||
}
|
||||
}
|
||||
return defaultValue;
|
||||
final float floatValue = val.floatValue();
|
||||
// if (Float.isNaN(floatValue) || Float.isInfinite(floatValue)) {
|
||||
// return floatValue;
|
||||
// }
|
||||
return floatValue;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -661,27 +639,18 @@ public class JSONArray implements Iterable<Object> {
|
||||
* @return The value.
|
||||
*/
|
||||
public int optInt(int index, int defaultValue) {
|
||||
Object val = this.opt(index);
|
||||
if (JSONObject.NULL.equals(val)) {
|
||||
final Number val = this.optNumber(index, null);
|
||||
if (val == null) {
|
||||
return defaultValue;
|
||||
}
|
||||
if (val instanceof Number){
|
||||
return ((Number) val).intValue();
|
||||
}
|
||||
|
||||
if (val instanceof String) {
|
||||
try {
|
||||
return new BigDecimal(val.toString()).intValue();
|
||||
} catch (Exception e) {
|
||||
return defaultValue;
|
||||
}
|
||||
}
|
||||
return defaultValue;
|
||||
return val.intValue();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the enum value associated with a key.
|
||||
*
|
||||
* @param <E>
|
||||
* Enum Type
|
||||
* @param clazz
|
||||
* The type of enum to retrieve.
|
||||
* @param index
|
||||
@@ -695,6 +664,8 @@ public class JSONArray implements Iterable<Object> {
|
||||
/**
|
||||
* Get the enum value associated with a key.
|
||||
*
|
||||
* @param <E>
|
||||
* Enum Type
|
||||
* @param clazz
|
||||
* The type of enum to retrieve.
|
||||
* @param index
|
||||
@@ -724,7 +695,6 @@ public class JSONArray implements Iterable<Object> {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Get the optional BigInteger value associated with an index. The
|
||||
* defaultValue is returned if there is no value for the index, or if the
|
||||
@@ -738,37 +708,16 @@ public class JSONArray implements Iterable<Object> {
|
||||
*/
|
||||
public BigInteger optBigInteger(int index, BigInteger defaultValue) {
|
||||
Object val = this.opt(index);
|
||||
if (JSONObject.NULL.equals(val)) {
|
||||
return defaultValue;
|
||||
}
|
||||
if (val instanceof BigInteger){
|
||||
return (BigInteger) val;
|
||||
}
|
||||
if (val instanceof BigDecimal){
|
||||
return ((BigDecimal) val).toBigInteger();
|
||||
}
|
||||
if (val instanceof Double || val instanceof Float){
|
||||
return new BigDecimal(((Number) val).doubleValue()).toBigInteger();
|
||||
}
|
||||
if (val instanceof Long || val instanceof Integer
|
||||
|| val instanceof Short || val instanceof Byte){
|
||||
return BigInteger.valueOf(((Number) val).longValue());
|
||||
}
|
||||
try {
|
||||
final String valStr = val.toString();
|
||||
if(JSONObject.isDecimalNotation(valStr)) {
|
||||
return new BigDecimal(valStr).toBigInteger();
|
||||
}
|
||||
return new BigInteger(valStr);
|
||||
} catch (Exception e) {
|
||||
return defaultValue;
|
||||
}
|
||||
return JSONObject.objectToBigInteger(val, defaultValue);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the optional BigDecimal value associated with an index. 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. If the value
|
||||
* is float or double, the the {@link BigDecimal#BigDecimal(double)}
|
||||
* constructor will be used. See notes on the constructor for conversion
|
||||
* issues that may arise.
|
||||
*
|
||||
* @param index
|
||||
* The index must be between 0 and length() - 1.
|
||||
@@ -778,27 +727,7 @@ public class JSONArray implements Iterable<Object> {
|
||||
*/
|
||||
public BigDecimal optBigDecimal(int index, BigDecimal defaultValue) {
|
||||
Object val = this.opt(index);
|
||||
if (JSONObject.NULL.equals(val)) {
|
||||
return defaultValue;
|
||||
}
|
||||
if (val instanceof BigDecimal){
|
||||
return (BigDecimal) val;
|
||||
}
|
||||
if (val instanceof BigInteger){
|
||||
return new BigDecimal((BigInteger) val);
|
||||
}
|
||||
if (val instanceof Double || val instanceof Float){
|
||||
return new BigDecimal(((Number) val).doubleValue());
|
||||
}
|
||||
if (val instanceof Long || val instanceof Integer
|
||||
|| val instanceof Short || val instanceof Byte){
|
||||
return new BigDecimal(((Number) val).longValue());
|
||||
}
|
||||
try {
|
||||
return new BigDecimal(val.toString());
|
||||
} catch (Exception e) {
|
||||
return defaultValue;
|
||||
}
|
||||
return JSONObject.objectToBigDecimal(val, defaultValue);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -853,22 +782,11 @@ public class JSONArray implements Iterable<Object> {
|
||||
* @return The value.
|
||||
*/
|
||||
public long optLong(int index, long defaultValue) {
|
||||
Object val = this.opt(index);
|
||||
if (JSONObject.NULL.equals(val)) {
|
||||
final Number val = this.optNumber(index, null);
|
||||
if (val == null) {
|
||||
return defaultValue;
|
||||
}
|
||||
if (val instanceof Number){
|
||||
return ((Number) val).longValue();
|
||||
}
|
||||
|
||||
if (val instanceof String) {
|
||||
try {
|
||||
return new BigDecimal(val.toString()).longValue();
|
||||
} catch (Exception e) {
|
||||
return defaultValue;
|
||||
}
|
||||
}
|
||||
return defaultValue;
|
||||
return val.longValue();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -953,8 +871,7 @@ public class JSONArray implements Iterable<Object> {
|
||||
* @return this.
|
||||
*/
|
||||
public JSONArray put(boolean value) {
|
||||
this.put(value ? Boolean.TRUE : Boolean.FALSE);
|
||||
return this;
|
||||
return this.put(value ? Boolean.TRUE : Boolean.FALSE);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -964,10 +881,11 @@ public class JSONArray implements Iterable<Object> {
|
||||
* @param value
|
||||
* A Collection value.
|
||||
* @return this.
|
||||
* @throws JSONException
|
||||
* If the value is non-finite number.
|
||||
*/
|
||||
public JSONArray put(Collection<?> value) {
|
||||
this.put(new JSONArray(value));
|
||||
return this;
|
||||
return this.put(new JSONArray(value));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -975,15 +893,25 @@ public class JSONArray implements Iterable<Object> {
|
||||
*
|
||||
* @param value
|
||||
* A double value.
|
||||
* @return this.
|
||||
* @throws JSONException
|
||||
* if the value is not finite.
|
||||
* @return this.
|
||||
*/
|
||||
public JSONArray put(double value) throws JSONException {
|
||||
Double d = new Double(value);
|
||||
JSONObject.testValidity(d);
|
||||
this.put(d);
|
||||
return this;
|
||||
return this.put(Double.valueOf(value));
|
||||
}
|
||||
|
||||
/**
|
||||
* Append a float value. This increases the array's length by one.
|
||||
*
|
||||
* @param value
|
||||
* A float value.
|
||||
* @return this.
|
||||
* @throws JSONException
|
||||
* if the value is not finite.
|
||||
*/
|
||||
public JSONArray put(float value) throws JSONException {
|
||||
return this.put(Float.valueOf(value));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -994,8 +922,7 @@ public class JSONArray implements Iterable<Object> {
|
||||
* @return this.
|
||||
*/
|
||||
public JSONArray put(int value) {
|
||||
this.put(new Integer(value));
|
||||
return this;
|
||||
return this.put(Integer.valueOf(value));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1006,8 +933,7 @@ public class JSONArray implements Iterable<Object> {
|
||||
* @return this.
|
||||
*/
|
||||
public JSONArray put(long value) {
|
||||
this.put(new Long(value));
|
||||
return this;
|
||||
return this.put(Long.valueOf(value));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1017,10 +943,13 @@ public class JSONArray implements Iterable<Object> {
|
||||
* @param value
|
||||
* A Map value.
|
||||
* @return this.
|
||||
* @throws JSONException
|
||||
* If a value in the map is non-finite number.
|
||||
* @throws NullPointerException
|
||||
* If a key in the map is <code>null</code>
|
||||
*/
|
||||
public JSONArray put(Map<?, ?> value) {
|
||||
this.put(new JSONObject(value));
|
||||
return this;
|
||||
return this.put(new JSONObject(value));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1031,8 +960,11 @@ public class JSONArray implements Iterable<Object> {
|
||||
* Integer, JSONArray, JSONObject, Long, or String, or the
|
||||
* JSONObject.NULL object.
|
||||
* @return this.
|
||||
* @throws JSONException
|
||||
* If the value is non-finite number.
|
||||
*/
|
||||
public JSONArray put(Object value) {
|
||||
JSONObject.testValidity(value);
|
||||
this.myArrayList.add(value);
|
||||
return this;
|
||||
}
|
||||
@@ -1051,8 +983,7 @@ public class JSONArray implements Iterable<Object> {
|
||||
* If the index is negative.
|
||||
*/
|
||||
public JSONArray put(int index, boolean value) throws JSONException {
|
||||
this.put(index, value ? Boolean.TRUE : Boolean.FALSE);
|
||||
return this;
|
||||
return this.put(index, value ? Boolean.TRUE : Boolean.FALSE);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1065,11 +996,10 @@ public class JSONArray implements Iterable<Object> {
|
||||
* A Collection value.
|
||||
* @return this.
|
||||
* @throws JSONException
|
||||
* If the index is negative or if the value is not finite.
|
||||
* If the index is negative or if the value is non-finite.
|
||||
*/
|
||||
public JSONArray put(int index, Collection<?> value) throws JSONException {
|
||||
this.put(index, new JSONArray(value));
|
||||
return this;
|
||||
return this.put(index, new JSONArray(value));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1083,11 +1013,27 @@ public class JSONArray implements Iterable<Object> {
|
||||
* A double value.
|
||||
* @return this.
|
||||
* @throws JSONException
|
||||
* If the index is negative or if the value is not finite.
|
||||
* If the index is negative or if the value is non-finite.
|
||||
*/
|
||||
public JSONArray put(int index, double value) throws JSONException {
|
||||
this.put(index, new Double(value));
|
||||
return this;
|
||||
return this.put(index, Double.valueOf(value));
|
||||
}
|
||||
|
||||
/**
|
||||
* Put or replace a float value. If the index is greater than the length of
|
||||
* the JSONArray, then null elements will be added as necessary to pad it
|
||||
* out.
|
||||
*
|
||||
* @param index
|
||||
* The subscript.
|
||||
* @param value
|
||||
* A float value.
|
||||
* @return this.
|
||||
* @throws JSONException
|
||||
* If the index is negative or if the value is non-finite.
|
||||
*/
|
||||
public JSONArray put(int index, float value) throws JSONException {
|
||||
return this.put(index, Float.valueOf(value));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1104,8 +1050,7 @@ public class JSONArray implements Iterable<Object> {
|
||||
* If the index is negative.
|
||||
*/
|
||||
public JSONArray put(int index, int value) throws JSONException {
|
||||
this.put(index, new Integer(value));
|
||||
return this;
|
||||
return this.put(index, Integer.valueOf(value));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1122,8 +1067,7 @@ public class JSONArray implements Iterable<Object> {
|
||||
* If the index is negative.
|
||||
*/
|
||||
public JSONArray put(int index, long value) throws JSONException {
|
||||
this.put(index, new Long(value));
|
||||
return this;
|
||||
return this.put(index, Long.valueOf(value));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1138,6 +1082,8 @@ public class JSONArray implements Iterable<Object> {
|
||||
* @throws JSONException
|
||||
* If the index is negative or if the the value is an invalid
|
||||
* number.
|
||||
* @throws NullPointerException
|
||||
* If a key in the map is <code>null</code>
|
||||
*/
|
||||
public JSONArray put(int index, Map<?, ?> value) throws JSONException {
|
||||
this.put(index, new JSONObject(value));
|
||||
@@ -1161,25 +1107,26 @@ public class JSONArray implements Iterable<Object> {
|
||||
* number.
|
||||
*/
|
||||
public JSONArray put(int index, Object value) throws JSONException {
|
||||
JSONObject.testValidity(value);
|
||||
if (index < 0) {
|
||||
throw new JSONException("JSONArray[" + index + "] not found.");
|
||||
}
|
||||
if (index < this.length()) {
|
||||
JSONObject.testValidity(value);
|
||||
this.myArrayList.set(index, value);
|
||||
} else if(index == this.length()){
|
||||
// simple append
|
||||
this.put(value);
|
||||
} else {
|
||||
// if we are inserting past the length, we want to grow the array all at once
|
||||
// instead of incrementally.
|
||||
this.myArrayList.ensureCapacity(index + 1);
|
||||
while (index != this.length()) {
|
||||
this.put(JSONObject.NULL);
|
||||
}
|
||||
this.put(value);
|
||||
return this;
|
||||
}
|
||||
return this;
|
||||
if(index == this.length()){
|
||||
// simple append
|
||||
return this.put(value);
|
||||
}
|
||||
// if we are inserting past the length, we want to grow the array all at once
|
||||
// instead of incrementally.
|
||||
this.myArrayList.ensureCapacity(index + 1);
|
||||
while (index != this.length()) {
|
||||
// we don't need to test validity of NULL objects
|
||||
this.myArrayList.add(JSONObject.NULL);
|
||||
}
|
||||
return this.put(value);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1206,8 +1153,8 @@ public class JSONArray implements Iterable<Object> {
|
||||
}
|
||||
|
||||
/**
|
||||
* Uses a uaer initialized JSONPointer and tries to
|
||||
* match it to an item whithin this JSONArray. For example, given a
|
||||
* Uses a user initialized JSONPointer and tries to
|
||||
* match it to an item within this JSONArray. For example, given a
|
||||
* JSONArray initialized with this document:
|
||||
* <pre>
|
||||
* [
|
||||
@@ -1322,7 +1269,7 @@ public class JSONArray implements Iterable<Object> {
|
||||
* If any of the names are null.
|
||||
*/
|
||||
public JSONObject toJSONObject(JSONArray names) throws JSONException {
|
||||
if (names == null || names.length() == 0 || this.length() == 0) {
|
||||
if (names == null || names.isEmpty() || this.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
JSONObject jo = new JSONObject(names.length());
|
||||
@@ -1498,4 +1445,14 @@ public class JSONArray implements Iterable<Object> {
|
||||
}
|
||||
return results;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if JSONArray is empty.
|
||||
*
|
||||
* @return true if JSONArray is empty, otherwise false.
|
||||
*/
|
||||
public boolean isEmpty() {
|
||||
return this.myArrayList.isEmpty();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
597
JSONObject.java
597
JSONObject.java
@@ -29,6 +29,7 @@ import java.io.Closeable;
|
||||
import java.io.IOException;
|
||||
import java.io.StringWriter;
|
||||
import java.io.Writer;
|
||||
import java.lang.annotation.Annotation;
|
||||
import java.lang.reflect.Field;
|
||||
import java.lang.reflect.InvocationTargetException;
|
||||
import java.lang.reflect.Method;
|
||||
@@ -44,6 +45,7 @@ import java.util.Map;
|
||||
import java.util.Map.Entry;
|
||||
import java.util.ResourceBundle;
|
||||
import java.util.Set;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* A JSONObject is an unordered collection of name/value pairs. Its external
|
||||
@@ -149,6 +151,12 @@ public class JSONObject {
|
||||
return "null";
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Regular Expression Pattern that matches JSON Numbers. This is primarily used for
|
||||
* output to guarantee that we are always writing valid JSON.
|
||||
*/
|
||||
static final Pattern NUMBER_PATTERN = Pattern.compile("-?(?:0|[1-9]\\d*)(?:\\.\\d+)?(?:[eE][+-]?\\d+)?");
|
||||
|
||||
/**
|
||||
* The map where the JSONObject's properties are kept.
|
||||
@@ -271,6 +279,10 @@ public class JSONObject {
|
||||
* @param m
|
||||
* A map object that can be used to initialize the contents of
|
||||
* the JSONObject.
|
||||
* @throws JSONException
|
||||
* If a value in the map is non-finite number.
|
||||
* @throws NullPointerException
|
||||
* If a key in the map is <code>null</code>
|
||||
*/
|
||||
public JSONObject(Map<?, ?> m) {
|
||||
if (m == null) {
|
||||
@@ -278,6 +290,9 @@ public class JSONObject {
|
||||
} else {
|
||||
this.map = new HashMap<String, Object>(m.size());
|
||||
for (final Entry<?, ?> e : m.entrySet()) {
|
||||
if(e.getKey() == null) {
|
||||
throw new NullPointerException("Null key.");
|
||||
}
|
||||
final Object value = e.getValue();
|
||||
if (value != null) {
|
||||
this.map.put(String.valueOf(e.getKey()), wrap(value));
|
||||
@@ -298,13 +313,47 @@ public class JSONObject {
|
||||
* prefix. If the second remaining character is not upper case, then the
|
||||
* first character is converted to lower case.
|
||||
* <p>
|
||||
* Methods that are <code>static</code>, return <code>void</code>,
|
||||
* have parameters, or are "bridge" methods, are ignored.
|
||||
* <p>
|
||||
* For example, if an object has a method named <code>"getName"</code>, and
|
||||
* if the result of calling <code>object.getName()</code> is
|
||||
* <code>"Larry Fine"</code>, then the JSONObject will contain
|
||||
* <code>"name": "Larry Fine"</code>.
|
||||
* <p>
|
||||
* Methods that return <code>void</code> as well as <code>static</code>
|
||||
* methods are ignored.
|
||||
* The {@link JSONPropertyName} annotation can be used on a bean getter to
|
||||
* override key name used in the JSONObject. For example, using the object
|
||||
* above with the <code>getName</code> method, if we annotated it with:
|
||||
* <pre>
|
||||
* @JSONPropertyName("FullName")
|
||||
* public String getName() { return this.name; }
|
||||
* </pre>
|
||||
* The resulting JSON object would contain <code>"FullName": "Larry Fine"</code>
|
||||
* <p>
|
||||
* Similarly, the {@link JSONPropertyName} annotation can be used on non-
|
||||
* <code>get</code> and <code>is</code> methods. We can also override key
|
||||
* name used in the JSONObject as seen below even though the field would normally
|
||||
* be ignored:
|
||||
* <pre>
|
||||
* @JSONPropertyName("FullName")
|
||||
* public String fullName() { return this.name; }
|
||||
* </pre>
|
||||
* The resulting JSON object would contain <code>"FullName": "Larry Fine"</code>
|
||||
* <p>
|
||||
* The {@link JSONPropertyIgnore} annotation can be used to force the bean property
|
||||
* to not be serialized into JSON. If both {@link JSONPropertyIgnore} and
|
||||
* {@link JSONPropertyName} are defined on the same method, a depth comparison is
|
||||
* performed and the one closest to the concrete class being serialized is used.
|
||||
* If both annotations are at the same level, then the {@link JSONPropertyIgnore}
|
||||
* annotation takes precedent and the field is not serialized.
|
||||
* For example, the following declaration would prevent the <code>getName</code>
|
||||
* method from being serialized:
|
||||
* <pre>
|
||||
* @JSONPropertyName("FullName")
|
||||
* @JSONPropertyIgnore
|
||||
* public String getName() { return this.name; }
|
||||
* </pre>
|
||||
* <p>
|
||||
*
|
||||
* @param bean
|
||||
* An object that has getter methods that should be used to make
|
||||
@@ -428,7 +477,9 @@ public class JSONObject {
|
||||
* 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.
|
||||
* If the value is non-finite number.
|
||||
* @throws NullPointerException
|
||||
* If the key is <code>null</code>.
|
||||
*/
|
||||
public JSONObject accumulate(String key, Object value) throws JSONException {
|
||||
testValidity(value);
|
||||
@@ -457,8 +508,10 @@ public class JSONObject {
|
||||
* An object to be accumulated under the key.
|
||||
* @return this.
|
||||
* @throws JSONException
|
||||
* If the key is null or if the current value associated with
|
||||
* If the value is non-finite number or if the current value associated with
|
||||
* the key is not a JSONArray.
|
||||
* @throws NullPointerException
|
||||
* If the key is <code>null</code>.
|
||||
*/
|
||||
public JSONObject append(String key, Object value) throws JSONException {
|
||||
testValidity(value);
|
||||
@@ -523,17 +576,19 @@ public class JSONObject {
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the enum value associated with a key.
|
||||
*
|
||||
* @param clazz
|
||||
* The type of enum to retrieve.
|
||||
* @param key
|
||||
* A key string.
|
||||
* @return The enum value associated with the key
|
||||
* @throws JSONException
|
||||
* if the key is not found or if the value cannot be converted
|
||||
* to an enum.
|
||||
*/
|
||||
* Get the enum value associated with a key.
|
||||
*
|
||||
* @param <E>
|
||||
* Enum Type
|
||||
* @param clazz
|
||||
* The type of enum to retrieve.
|
||||
* @param key
|
||||
* A key string.
|
||||
* @return The enum value associated with the key
|
||||
* @throws JSONException
|
||||
* if the key is not found or if the value cannot be converted
|
||||
* to an enum.
|
||||
*/
|
||||
public <E extends Enum<E>> E getEnum(Class<E> clazz, String key) throws JSONException {
|
||||
E val = optEnum(clazz, key);
|
||||
if(val==null) {
|
||||
@@ -584,16 +639,19 @@ public class JSONObject {
|
||||
*/
|
||||
public BigInteger getBigInteger(String key) throws JSONException {
|
||||
Object object = this.get(key);
|
||||
try {
|
||||
return new BigInteger(object.toString());
|
||||
} catch (Exception e) {
|
||||
throw new JSONException("JSONObject[" + quote(key)
|
||||
+ "] could not be converted to BigInteger.", e);
|
||||
BigInteger ret = objectToBigInteger(object, null);
|
||||
if (ret != null) {
|
||||
return ret;
|
||||
}
|
||||
throw new JSONException("JSONObject[" + quote(key)
|
||||
+ "] could not be converted to BigInteger (" + object + ").");
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the BigDecimal value associated with a key.
|
||||
* Get the BigDecimal value associated with a key. If the value is float or
|
||||
* double, the the {@link BigDecimal#BigDecimal(double)} constructor will
|
||||
* be used. See notes on the constructor for conversion issues that may
|
||||
* arise.
|
||||
*
|
||||
* @param key
|
||||
* A key string.
|
||||
@@ -604,15 +662,12 @@ public class JSONObject {
|
||||
*/
|
||||
public BigDecimal getBigDecimal(String key) throws JSONException {
|
||||
Object object = this.get(key);
|
||||
if (object instanceof BigDecimal) {
|
||||
return (BigDecimal)object;
|
||||
}
|
||||
try {
|
||||
return new BigDecimal(object.toString());
|
||||
} catch (Exception e) {
|
||||
throw new JSONException("JSONObject[" + quote(key)
|
||||
+ "] could not be converted to BigDecimal.", e);
|
||||
BigDecimal ret = objectToBigDecimal(object, null);
|
||||
if (ret != null) {
|
||||
return ret;
|
||||
}
|
||||
throw new JSONException("JSONObject[" + quote(key)
|
||||
+ "] could not be converted to BigDecimal (" + object + ").");
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -626,14 +681,7 @@ public class JSONObject {
|
||||
* object and cannot be converted to a number.
|
||||
*/
|
||||
public double getDouble(String key) throws JSONException {
|
||||
Object object = this.get(key);
|
||||
try {
|
||||
return object instanceof Number ? ((Number) object).doubleValue()
|
||||
: Double.parseDouble(object.toString());
|
||||
} catch (Exception e) {
|
||||
throw new JSONException("JSONObject[" + quote(key)
|
||||
+ "] is not a number.", e);
|
||||
}
|
||||
return this.getNumber(key).doubleValue();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -647,14 +695,7 @@ public class JSONObject {
|
||||
* object and cannot be converted to a number.
|
||||
*/
|
||||
public float getFloat(String key) throws JSONException {
|
||||
Object object = this.get(key);
|
||||
try {
|
||||
return object instanceof Number ? ((Number) object).floatValue()
|
||||
: Float.parseFloat(object.toString());
|
||||
} catch (Exception e) {
|
||||
throw new JSONException("JSONObject[" + quote(key)
|
||||
+ "] is not a number.", e);
|
||||
}
|
||||
return this.getNumber(key).floatValue();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -691,14 +732,7 @@ public class JSONObject {
|
||||
* to an integer.
|
||||
*/
|
||||
public int getInt(String key) throws JSONException {
|
||||
Object object = this.get(key);
|
||||
try {
|
||||
return object instanceof Number ? ((Number) object).intValue()
|
||||
: Integer.parseInt((String) object);
|
||||
} catch (Exception e) {
|
||||
throw new JSONException("JSONObject[" + quote(key)
|
||||
+ "] is not an int.", e);
|
||||
}
|
||||
return this.getNumber(key).intValue();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -748,32 +782,28 @@ public class JSONObject {
|
||||
* to a long.
|
||||
*/
|
||||
public long getLong(String key) throws JSONException {
|
||||
Object object = this.get(key);
|
||||
try {
|
||||
return object instanceof Number ? ((Number) object).longValue()
|
||||
: Long.parseLong((String) object);
|
||||
} catch (Exception e) {
|
||||
throw new JSONException("JSONObject[" + quote(key)
|
||||
+ "] is not a long.", e);
|
||||
}
|
||||
return this.getNumber(key).longValue();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get an array of field names from a JSONObject.
|
||||
*
|
||||
* @param jo
|
||||
* JSON object
|
||||
* @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) {
|
||||
if (jo.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
return jo.keySet().toArray(new String[length]);
|
||||
return jo.keySet().toArray(new String[jo.length()]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get an array of field names from an Object.
|
||||
* Get an array of public field names from an Object.
|
||||
*
|
||||
* @param object
|
||||
* object to read
|
||||
* @return An array of field names, or null if there are no names.
|
||||
*/
|
||||
public static String[] getNames(Object object) {
|
||||
@@ -856,13 +886,13 @@ public class JSONObject {
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine if the value associated with the key is null or if there is no
|
||||
* Determine if the value associated with the key is <code>null</code> or if there is no
|
||||
* value.
|
||||
*
|
||||
* @param key
|
||||
* A key string.
|
||||
* @return true if there is no value associated with the key or if the value
|
||||
* is the JSONObject.NULL object.
|
||||
* is the JSONObject.NULL object.
|
||||
*/
|
||||
public boolean isNull(String key) {
|
||||
return JSONObject.NULL.equals(this.opt(key));
|
||||
@@ -917,12 +947,21 @@ public class JSONObject {
|
||||
return this.map.size();
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if JSONObject is empty.
|
||||
*
|
||||
* @return true if JSONObject is empty, otherwise false.
|
||||
*/
|
||||
public boolean isEmpty() {
|
||||
return this.map.isEmpty();
|
||||
}
|
||||
|
||||
/**
|
||||
* Produce a JSONArray containing the names of the elements of this
|
||||
* JSONObject.
|
||||
*
|
||||
* @return A JSONArray containing the key strings, or null if the JSONObject
|
||||
* is empty.
|
||||
* is empty.
|
||||
*/
|
||||
public JSONArray names() {
|
||||
if(this.map.isEmpty()) {
|
||||
@@ -975,6 +1014,8 @@ public class JSONObject {
|
||||
/**
|
||||
* Get the enum value associated with a key.
|
||||
*
|
||||
* @param <E>
|
||||
* Enum Type
|
||||
* @param clazz
|
||||
* The type of enum to retrieve.
|
||||
* @param key
|
||||
@@ -988,6 +1029,8 @@ public class JSONObject {
|
||||
/**
|
||||
* Get the enum value associated with a key.
|
||||
*
|
||||
* @param <E>
|
||||
* Enum Type
|
||||
* @param clazz
|
||||
* The type of enum to retrieve.
|
||||
* @param key
|
||||
@@ -1059,7 +1102,10 @@ public class JSONObject {
|
||||
/**
|
||||
* Get an optional BigDecimal associated with a key, or the defaultValue if
|
||||
* there is no such key or if its value is not a number. If the value is a
|
||||
* string, an attempt will be made to evaluate it as a number.
|
||||
* string, an attempt will be made to evaluate it as a number. If the value
|
||||
* is float or double, then the {@link BigDecimal#BigDecimal(double)}
|
||||
* constructor will be used. See notes on the constructor for conversion
|
||||
* issues that may arise.
|
||||
*
|
||||
* @param key
|
||||
* A key string.
|
||||
@@ -1069,6 +1115,16 @@ public class JSONObject {
|
||||
*/
|
||||
public BigDecimal optBigDecimal(String key, BigDecimal defaultValue) {
|
||||
Object val = this.opt(key);
|
||||
return objectToBigDecimal(val, defaultValue);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param val value to convert
|
||||
* @param defaultValue default value to return is the conversion doesn't work or is null.
|
||||
* @return BigDecimal conversion of the original value, or the defaultValue if unable
|
||||
* to convert.
|
||||
*/
|
||||
static BigDecimal objectToBigDecimal(Object val, BigDecimal defaultValue) {
|
||||
if (NULL.equals(val)) {
|
||||
return defaultValue;
|
||||
}
|
||||
@@ -1079,6 +1135,10 @@ public class JSONObject {
|
||||
return new BigDecimal((BigInteger) val);
|
||||
}
|
||||
if (val instanceof Double || val instanceof Float){
|
||||
final double d = ((Number) val).doubleValue();
|
||||
if(Double.isNaN(d)) {
|
||||
return defaultValue;
|
||||
}
|
||||
return new BigDecimal(((Number) val).doubleValue());
|
||||
}
|
||||
if (val instanceof Long || val instanceof Integer
|
||||
@@ -1106,6 +1166,16 @@ public class JSONObject {
|
||||
*/
|
||||
public BigInteger optBigInteger(String key, BigInteger defaultValue) {
|
||||
Object val = this.opt(key);
|
||||
return objectToBigInteger(val, defaultValue);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param val value to convert
|
||||
* @param defaultValue default value to return is the conversion doesn't work or is null.
|
||||
* @return BigInteger conversion of the original value, or the defaultValue if unable
|
||||
* to convert.
|
||||
*/
|
||||
static BigInteger objectToBigInteger(Object val, BigInteger defaultValue) {
|
||||
if (NULL.equals(val)) {
|
||||
return defaultValue;
|
||||
}
|
||||
@@ -1116,7 +1186,11 @@ public class JSONObject {
|
||||
return ((BigDecimal) val).toBigInteger();
|
||||
}
|
||||
if (val instanceof Double || val instanceof Float){
|
||||
return new BigDecimal(((Number) val).doubleValue()).toBigInteger();
|
||||
final double d = ((Number) val).doubleValue();
|
||||
if(Double.isNaN(d)) {
|
||||
return defaultValue;
|
||||
}
|
||||
return new BigDecimal(d).toBigInteger();
|
||||
}
|
||||
if (val instanceof Long || val instanceof Integer
|
||||
|| val instanceof Short || val instanceof Byte){
|
||||
@@ -1164,21 +1238,15 @@ public class JSONObject {
|
||||
* @return An object which is the value.
|
||||
*/
|
||||
public double optDouble(String key, double defaultValue) {
|
||||
Object val = this.opt(key);
|
||||
if (NULL.equals(val)) {
|
||||
Number val = this.optNumber(key);
|
||||
if (val == null) {
|
||||
return defaultValue;
|
||||
}
|
||||
if (val instanceof Number){
|
||||
return ((Number) val).doubleValue();
|
||||
}
|
||||
if (val instanceof String) {
|
||||
try {
|
||||
return Double.parseDouble((String) val);
|
||||
} catch (Exception e) {
|
||||
return defaultValue;
|
||||
}
|
||||
}
|
||||
return defaultValue;
|
||||
final double doubleValue = val.doubleValue();
|
||||
// if (Double.isNaN(doubleValue) || Double.isInfinite(doubleValue)) {
|
||||
// return defaultValue;
|
||||
// }
|
||||
return doubleValue;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1206,21 +1274,15 @@ public class JSONObject {
|
||||
* @return The value.
|
||||
*/
|
||||
public float optFloat(String key, float defaultValue) {
|
||||
Object val = this.opt(key);
|
||||
if (JSONObject.NULL.equals(val)) {
|
||||
Number val = this.optNumber(key);
|
||||
if (val == null) {
|
||||
return defaultValue;
|
||||
}
|
||||
if (val instanceof Number){
|
||||
return ((Number) val).floatValue();
|
||||
}
|
||||
if (val instanceof String) {
|
||||
try {
|
||||
return Float.parseFloat((String) val);
|
||||
} catch (Exception e) {
|
||||
return defaultValue;
|
||||
}
|
||||
}
|
||||
return defaultValue;
|
||||
final float floatValue = val.floatValue();
|
||||
// if (Float.isNaN(floatValue) || Float.isInfinite(floatValue)) {
|
||||
// return defaultValue;
|
||||
// }
|
||||
return floatValue;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1248,22 +1310,11 @@ public class JSONObject {
|
||||
* @return An object which is the value.
|
||||
*/
|
||||
public int optInt(String key, int defaultValue) {
|
||||
Object val = this.opt(key);
|
||||
if (NULL.equals(val)) {
|
||||
final Number val = this.optNumber(key, null);
|
||||
if (val == null) {
|
||||
return defaultValue;
|
||||
}
|
||||
if (val instanceof Number){
|
||||
return ((Number) val).intValue();
|
||||
}
|
||||
|
||||
if (val instanceof String) {
|
||||
try {
|
||||
return new BigDecimal((String) val).intValue();
|
||||
} catch (Exception e) {
|
||||
return defaultValue;
|
||||
}
|
||||
}
|
||||
return defaultValue;
|
||||
return val.intValue();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1317,22 +1368,12 @@ public class JSONObject {
|
||||
* @return An object which is the value.
|
||||
*/
|
||||
public long optLong(String key, long defaultValue) {
|
||||
Object val = this.opt(key);
|
||||
if (NULL.equals(val)) {
|
||||
final Number val = this.optNumber(key, null);
|
||||
if (val == null) {
|
||||
return defaultValue;
|
||||
}
|
||||
if (val instanceof Number){
|
||||
return ((Number) val).longValue();
|
||||
}
|
||||
|
||||
if (val instanceof String) {
|
||||
try {
|
||||
return new BigDecimal((String) val).longValue();
|
||||
} catch (Exception e) {
|
||||
return defaultValue;
|
||||
}
|
||||
}
|
||||
return defaultValue;
|
||||
return val.longValue();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1370,14 +1411,11 @@ public class JSONObject {
|
||||
return (Number) val;
|
||||
}
|
||||
|
||||
if (val instanceof String) {
|
||||
try {
|
||||
return stringToNumber((String) val);
|
||||
} catch (Exception e) {
|
||||
return defaultValue;
|
||||
}
|
||||
try {
|
||||
return stringToNumber(val.toString());
|
||||
} catch (Exception e) {
|
||||
return defaultValue;
|
||||
}
|
||||
return defaultValue;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1409,8 +1447,8 @@ public class JSONObject {
|
||||
}
|
||||
|
||||
/**
|
||||
* Populates the internal map of the JSONObject with the bean properties.
|
||||
* The bean can not be recursive.
|
||||
* Populates the internal map of the JSONObject with the bean properties. The
|
||||
* bean can not be recursive.
|
||||
*
|
||||
* @see JSONObject#JSONObject(Object)
|
||||
*
|
||||
@@ -1420,49 +1458,31 @@ public class JSONObject {
|
||||
private void populateMap(Object bean) {
|
||||
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;
|
||||
|
||||
Method[] methods = includeSuperClass ? klass.getMethods() : klass
|
||||
.getDeclaredMethods();
|
||||
Method[] methods = includeSuperClass ? klass.getMethods() : klass.getDeclaredMethods();
|
||||
for (final Method method : methods) {
|
||||
final int modifiers = method.getModifiers();
|
||||
if (Modifier.isPublic(modifiers)
|
||||
&& !Modifier.isStatic(modifiers)
|
||||
&& method.getParameterTypes().length == 0
|
||||
&& !method.isBridge()
|
||||
&& method.getReturnType() != Void.TYPE ) {
|
||||
final String name = method.getName();
|
||||
String key;
|
||||
if (name.startsWith("get")) {
|
||||
if ("getClass".equals(name) || "getDeclaringClass".equals(name)) {
|
||||
continue;
|
||||
}
|
||||
key = name.substring(3);
|
||||
} else if (name.startsWith("is")) {
|
||||
key = name.substring(2);
|
||||
} else {
|
||||
continue;
|
||||
}
|
||||
if (key.length() > 0
|
||||
&& Character.isUpperCase(key.charAt(0))) {
|
||||
if (key.length() == 1) {
|
||||
key = key.toLowerCase(Locale.ROOT);
|
||||
} else if (!Character.isUpperCase(key.charAt(1))) {
|
||||
key = key.substring(0, 1).toLowerCase(Locale.ROOT)
|
||||
+ key.substring(1);
|
||||
}
|
||||
|
||||
&& method.getReturnType() != Void.TYPE
|
||||
&& isValidMethodName(method.getName())) {
|
||||
final String key = getKeyNameFromMethod(method);
|
||||
if (key != null && !key.isEmpty()) {
|
||||
try {
|
||||
final Object result = method.invoke(bean);
|
||||
if (result != null) {
|
||||
this.map.put(key, wrap(result));
|
||||
// we don't use the result anywhere outside of wrap
|
||||
// if it's a resource we should be sure to close it after calling toString
|
||||
if(result instanceof Closeable) {
|
||||
// if it's a resource we should be sure to close it
|
||||
// after calling toString
|
||||
if (result instanceof Closeable) {
|
||||
try {
|
||||
((Closeable)result).close();
|
||||
((Closeable) result).close();
|
||||
} catch (IOException ignore) {
|
||||
}
|
||||
}
|
||||
@@ -1476,6 +1496,162 @@ public class JSONObject {
|
||||
}
|
||||
}
|
||||
|
||||
private boolean isValidMethodName(String name) {
|
||||
return !"getClass".equals(name) && !"getDeclaringClass".equals(name);
|
||||
}
|
||||
|
||||
private String getKeyNameFromMethod(Method method) {
|
||||
final int ignoreDepth = getAnnotationDepth(method, JSONPropertyIgnore.class);
|
||||
if (ignoreDepth > 0) {
|
||||
final int forcedNameDepth = getAnnotationDepth(method, JSONPropertyName.class);
|
||||
if (forcedNameDepth < 0 || ignoreDepth <= forcedNameDepth) {
|
||||
// the hierarchy asked to ignore, and the nearest name override
|
||||
// was higher or non-existent
|
||||
return null;
|
||||
}
|
||||
}
|
||||
JSONPropertyName annotation = getAnnotation(method, JSONPropertyName.class);
|
||||
if (annotation != null && annotation.value() != null && !annotation.value().isEmpty()) {
|
||||
return annotation.value();
|
||||
}
|
||||
String key;
|
||||
final String name = method.getName();
|
||||
if (name.startsWith("get") && name.length() > 3) {
|
||||
key = name.substring(3);
|
||||
} else if (name.startsWith("is") && name.length() > 2) {
|
||||
key = name.substring(2);
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
// if the first letter in the key is not uppercase, then skip.
|
||||
// This is to maintain backwards compatibility before PR406
|
||||
// (https://github.com/stleary/JSON-java/pull/406/)
|
||||
if (Character.isLowerCase(key.charAt(0))) {
|
||||
return null;
|
||||
}
|
||||
if (key.length() == 1) {
|
||||
key = key.toLowerCase(Locale.ROOT);
|
||||
} else if (!Character.isUpperCase(key.charAt(1))) {
|
||||
key = key.substring(0, 1).toLowerCase(Locale.ROOT) + key.substring(1);
|
||||
}
|
||||
return key;
|
||||
}
|
||||
|
||||
/**
|
||||
* Searches the class hierarchy to see if the method or it's super
|
||||
* implementations and interfaces has the annotation.
|
||||
*
|
||||
* @param <A>
|
||||
* type of the annotation
|
||||
*
|
||||
* @param m
|
||||
* method to check
|
||||
* @param annotationClass
|
||||
* annotation to look for
|
||||
* @return the {@link Annotation} if the annotation exists on the current method
|
||||
* or one of it's super class definitions
|
||||
*/
|
||||
private static <A extends Annotation> A getAnnotation(final Method m, final Class<A> annotationClass) {
|
||||
// if we have invalid data the result is null
|
||||
if (m == null || annotationClass == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (m.isAnnotationPresent(annotationClass)) {
|
||||
return m.getAnnotation(annotationClass);
|
||||
}
|
||||
|
||||
// if we've already reached the Object class, return null;
|
||||
Class<?> c = m.getDeclaringClass();
|
||||
if (c.getSuperclass() == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// check directly implemented interfaces for the method being checked
|
||||
for (Class<?> i : c.getInterfaces()) {
|
||||
try {
|
||||
Method im = i.getMethod(m.getName(), m.getParameterTypes());
|
||||
return getAnnotation(im, annotationClass);
|
||||
} catch (final SecurityException ex) {
|
||||
continue;
|
||||
} catch (final NoSuchMethodException ex) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
return getAnnotation(
|
||||
c.getSuperclass().getMethod(m.getName(), m.getParameterTypes()),
|
||||
annotationClass);
|
||||
} catch (final SecurityException ex) {
|
||||
return null;
|
||||
} catch (final NoSuchMethodException ex) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Searches the class hierarchy to see if the method or it's super
|
||||
* implementations and interfaces has the annotation. Returns the depth of the
|
||||
* annotation in the hierarchy.
|
||||
*
|
||||
* @param <A>
|
||||
* type of the annotation
|
||||
*
|
||||
* @param m
|
||||
* method to check
|
||||
* @param annotationClass
|
||||
* annotation to look for
|
||||
* @return Depth of the annotation or -1 if the annotation is not on the method.
|
||||
*/
|
||||
private static int getAnnotationDepth(final Method m, final Class<? extends Annotation> annotationClass) {
|
||||
// if we have invalid data the result is -1
|
||||
if (m == null || annotationClass == null) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
if (m.isAnnotationPresent(annotationClass)) {
|
||||
return 1;
|
||||
}
|
||||
|
||||
// if we've already reached the Object class, return -1;
|
||||
Class<?> c = m.getDeclaringClass();
|
||||
if (c.getSuperclass() == null) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
// check directly implemented interfaces for the method being checked
|
||||
for (Class<?> i : c.getInterfaces()) {
|
||||
try {
|
||||
Method im = i.getMethod(m.getName(), m.getParameterTypes());
|
||||
int d = getAnnotationDepth(im, annotationClass);
|
||||
if (d > 0) {
|
||||
// since the annotation was on the interface, add 1
|
||||
return d + 1;
|
||||
}
|
||||
} catch (final SecurityException ex) {
|
||||
continue;
|
||||
} catch (final NoSuchMethodException ex) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
int d = getAnnotationDepth(
|
||||
c.getSuperclass().getMethod(m.getName(), m.getParameterTypes()),
|
||||
annotationClass);
|
||||
if (d > 0) {
|
||||
// since the annotation was on the superclass, add 1
|
||||
return d + 1;
|
||||
}
|
||||
return -1;
|
||||
} catch (final SecurityException ex) {
|
||||
return -1;
|
||||
} catch (final NoSuchMethodException ex) {
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Put a key/boolean pair in the JSONObject.
|
||||
*
|
||||
@@ -1485,11 +1661,12 @@ public class JSONObject {
|
||||
* A boolean which is the value.
|
||||
* @return this.
|
||||
* @throws JSONException
|
||||
* If the key is null.
|
||||
* If the value is non-finite number.
|
||||
* @throws NullPointerException
|
||||
* If the key is <code>null</code>.
|
||||
*/
|
||||
public JSONObject put(String key, boolean value) throws JSONException {
|
||||
this.put(key, value ? Boolean.TRUE : Boolean.FALSE);
|
||||
return this;
|
||||
return this.put(key, value ? Boolean.TRUE : Boolean.FALSE);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1502,10 +1679,12 @@ public class JSONObject {
|
||||
* A Collection value.
|
||||
* @return this.
|
||||
* @throws JSONException
|
||||
* If the value is non-finite number.
|
||||
* @throws NullPointerException
|
||||
* If the key is <code>null</code>.
|
||||
*/
|
||||
public JSONObject put(String key, Collection<?> value) throws JSONException {
|
||||
this.put(key, new JSONArray(value));
|
||||
return this;
|
||||
return this.put(key, new JSONArray(value));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1517,11 +1696,12 @@ public class JSONObject {
|
||||
* A double which is the value.
|
||||
* @return this.
|
||||
* @throws JSONException
|
||||
* If the key is null or if the number is invalid.
|
||||
* If the value is non-finite number.
|
||||
* @throws NullPointerException
|
||||
* If the key is <code>null</code>.
|
||||
*/
|
||||
public JSONObject put(String key, double value) throws JSONException {
|
||||
this.put(key, Double.valueOf(value));
|
||||
return this;
|
||||
return this.put(key, Double.valueOf(value));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1533,11 +1713,12 @@ public class JSONObject {
|
||||
* A float which is the value.
|
||||
* @return this.
|
||||
* @throws JSONException
|
||||
* If the key is null or if the number is invalid.
|
||||
* If the value is non-finite number.
|
||||
* @throws NullPointerException
|
||||
* If the key is <code>null</code>.
|
||||
*/
|
||||
public JSONObject put(String key, float value) throws JSONException {
|
||||
this.put(key, Float.valueOf(value));
|
||||
return this;
|
||||
return this.put(key, Float.valueOf(value));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1549,11 +1730,12 @@ public class JSONObject {
|
||||
* An int which is the value.
|
||||
* @return this.
|
||||
* @throws JSONException
|
||||
* If the key is null.
|
||||
* If the value is non-finite number.
|
||||
* @throws NullPointerException
|
||||
* If the key is <code>null</code>.
|
||||
*/
|
||||
public JSONObject put(String key, int value) throws JSONException {
|
||||
this.put(key, Integer.valueOf(value));
|
||||
return this;
|
||||
return this.put(key, Integer.valueOf(value));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1565,11 +1747,12 @@ public class JSONObject {
|
||||
* A long which is the value.
|
||||
* @return this.
|
||||
* @throws JSONException
|
||||
* If the key is null.
|
||||
* If the value is non-finite number.
|
||||
* @throws NullPointerException
|
||||
* If the key is <code>null</code>.
|
||||
*/
|
||||
public JSONObject put(String key, long value) throws JSONException {
|
||||
this.put(key, Long.valueOf(value));
|
||||
return this;
|
||||
return this.put(key, Long.valueOf(value));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1582,14 +1765,16 @@ public class JSONObject {
|
||||
* A Map value.
|
||||
* @return this.
|
||||
* @throws JSONException
|
||||
* If the value is non-finite number.
|
||||
* @throws NullPointerException
|
||||
* If the key is <code>null</code>.
|
||||
*/
|
||||
public JSONObject put(String key, Map<?, ?> value) throws JSONException {
|
||||
this.put(key, new JSONObject(value));
|
||||
return this;
|
||||
return this.put(key, new JSONObject(value));
|
||||
}
|
||||
|
||||
/**
|
||||
* Put a key/value pair in the JSONObject. If the value is null, then the
|
||||
* Put a key/value pair in the JSONObject. If the value is <code>null</code>, then the
|
||||
* key will be removed from the JSONObject if it is present.
|
||||
*
|
||||
* @param key
|
||||
@@ -1600,7 +1785,9 @@ public class JSONObject {
|
||||
* String, or the JSONObject.NULL object.
|
||||
* @return this.
|
||||
* @throws JSONException
|
||||
* If the value is non-finite number or if the key is null.
|
||||
* If the value is non-finite number.
|
||||
* @throws NullPointerException
|
||||
* If the key is <code>null</code>.
|
||||
*/
|
||||
public JSONObject put(String key, Object value) throws JSONException {
|
||||
if (key == null) {
|
||||
@@ -1620,8 +1807,10 @@ public class JSONObject {
|
||||
* are both non-null, and only if there is not already a member with that
|
||||
* name.
|
||||
*
|
||||
* @param key string
|
||||
* @param value object
|
||||
* @param key
|
||||
* key to insert into
|
||||
* @param value
|
||||
* value to insert
|
||||
* @return this.
|
||||
* @throws JSONException
|
||||
* if the key is a duplicate
|
||||
@@ -1631,7 +1820,7 @@ public class JSONObject {
|
||||
if (this.opt(key) != null) {
|
||||
throw new JSONException("Duplicate key \"" + key + "\"");
|
||||
}
|
||||
this.put(key, value);
|
||||
return this.put(key, value);
|
||||
}
|
||||
return this;
|
||||
}
|
||||
@@ -1652,7 +1841,7 @@ public class JSONObject {
|
||||
*/
|
||||
public JSONObject putOpt(String key, Object value) throws JSONException {
|
||||
if (key != null && value != null) {
|
||||
this.put(key, value);
|
||||
return this.put(key, value);
|
||||
}
|
||||
return this;
|
||||
}
|
||||
@@ -1732,9 +1921,10 @@ public class JSONObject {
|
||||
|
||||
/**
|
||||
* 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.
|
||||
* 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
|
||||
@@ -1753,7 +1943,7 @@ public class JSONObject {
|
||||
}
|
||||
|
||||
public static Writer quote(String string, Writer w) throws IOException {
|
||||
if (string == null || string.length() == 0) {
|
||||
if (string == null || string.isEmpty()) {
|
||||
w.write("\"\"");
|
||||
return w;
|
||||
}
|
||||
@@ -1947,22 +2137,26 @@ public class JSONObject {
|
||||
* can't be converted, return the string.
|
||||
*
|
||||
* @param string
|
||||
* A String.
|
||||
* A String. can not be null.
|
||||
* @return A simple JSON value.
|
||||
* @throws NullPointerException
|
||||
* Thrown if the string is null.
|
||||
*/
|
||||
// Changes to this method must be copied to the corresponding method in
|
||||
// the XML class to keep full support for Android
|
||||
public static Object stringToValue(String string) {
|
||||
if (string.equals("")) {
|
||||
if ("".equals(string)) {
|
||||
return string;
|
||||
}
|
||||
if (string.equalsIgnoreCase("true")) {
|
||||
|
||||
// check JSON key words true/false/null
|
||||
if ("true".equalsIgnoreCase(string)) {
|
||||
return Boolean.TRUE;
|
||||
}
|
||||
if (string.equalsIgnoreCase("false")) {
|
||||
if ("false".equalsIgnoreCase(string)) {
|
||||
return Boolean.FALSE;
|
||||
}
|
||||
if (string.equalsIgnoreCase("null")) {
|
||||
if ("null".equalsIgnoreCase(string)) {
|
||||
return JSONObject.NULL;
|
||||
}
|
||||
|
||||
@@ -1974,7 +2168,8 @@ public class JSONObject {
|
||||
char initial = string.charAt(0);
|
||||
if ((initial >= '0' && initial <= '9') || initial == '-') {
|
||||
try {
|
||||
// if we want full Big Number support this block can be replaced with:
|
||||
// if we want full Big Number support the contents of this
|
||||
// `try` block can be replaced with:
|
||||
// return stringToNumber(string);
|
||||
if (isDecimalNotation(string)) {
|
||||
Double d = Double.valueOf(string);
|
||||
@@ -2032,7 +2227,7 @@ public class JSONObject {
|
||||
* If any of the values are non-finite numbers.
|
||||
*/
|
||||
public JSONArray toJSONArray(JSONArray names) throws JSONException {
|
||||
if (names == null || names.length() == 0) {
|
||||
if (names == null || names.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
JSONArray ja = new JSONArray();
|
||||
@@ -2130,7 +2325,7 @@ public class JSONObject {
|
||||
}
|
||||
|
||||
/**
|
||||
* Wrap an object, if necessary. If the object is null, return the NULL
|
||||
* Wrap an object, if necessary. If the object is <code>null</code>, 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
|
||||
@@ -2211,13 +2406,9 @@ public class JSONObject {
|
||||
} 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 its parser to validate the format.
|
||||
@SuppressWarnings("unused")
|
||||
BigDecimal testNum = new BigDecimal(numberAsString);
|
||||
// Close enough to a JSON number that we will use it unquoted
|
||||
if(NUMBER_PATTERN.matcher(numberAsString).matches()) {
|
||||
writer.write(numberAsString);
|
||||
} catch (NumberFormatException ex){
|
||||
} else {
|
||||
// The Number value is not a valid JSON number.
|
||||
// Instead we will quote it as a string
|
||||
quote(numberAsString, writer);
|
||||
|
||||
@@ -158,9 +158,28 @@ public class JSONPointer {
|
||||
throw new IllegalArgumentException("a JSON pointer should start with '/' or '#/'");
|
||||
}
|
||||
this.refTokens = new ArrayList<String>();
|
||||
for (String token : refs.split("/")) {
|
||||
this.refTokens.add(unescape(token));
|
||||
}
|
||||
int slashIdx = -1;
|
||||
int prevSlashIdx = 0;
|
||||
do {
|
||||
prevSlashIdx = slashIdx + 1;
|
||||
slashIdx = refs.indexOf('/', prevSlashIdx);
|
||||
if(prevSlashIdx == slashIdx || prevSlashIdx == refs.length()) {
|
||||
// found 2 slashes in a row ( obj//next )
|
||||
// or single slash at the end of a string ( obj/test/ )
|
||||
this.refTokens.add("");
|
||||
} else if (slashIdx >= 0) {
|
||||
final String token = refs.substring(prevSlashIdx, slashIdx);
|
||||
this.refTokens.add(unescape(token));
|
||||
} else {
|
||||
// last item after separator, or no separator at all.
|
||||
final String token = refs.substring(prevSlashIdx);
|
||||
this.refTokens.add(unescape(token));
|
||||
}
|
||||
} while (slashIdx >= 0);
|
||||
// using split does not take into account consecutive separators or "ending nulls"
|
||||
//for (String token : refs.split("/")) {
|
||||
// this.refTokens.add(unescape(token));
|
||||
//}
|
||||
}
|
||||
|
||||
public JSONPointer(List<String> refTokens) {
|
||||
@@ -214,8 +233,8 @@ public class JSONPointer {
|
||||
int index = Integer.parseInt(indexToken);
|
||||
JSONArray currentArr = (JSONArray) current;
|
||||
if (index >= currentArr.length()) {
|
||||
throw new JSONPointerException(format("index %d is out of bounds - the array has %d elements", index,
|
||||
currentArr.length()));
|
||||
throw new JSONPointerException(format("index %s is out of bounds - the array has %d elements", indexToken,
|
||||
Integer.valueOf(currentArr.length())));
|
||||
}
|
||||
try {
|
||||
return currentArr.get(index);
|
||||
|
||||
43
JSONPropertyIgnore.java
Normal file
43
JSONPropertyIgnore.java
Normal file
@@ -0,0 +1,43 @@
|
||||
package org.json;
|
||||
|
||||
/*
|
||||
Copyright (c) 2018 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 static java.lang.annotation.ElementType.METHOD;
|
||||
import static java.lang.annotation.RetentionPolicy.RUNTIME;
|
||||
|
||||
import java.lang.annotation.Documented;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
@Documented
|
||||
@Retention(RUNTIME)
|
||||
@Target({METHOD})
|
||||
/**
|
||||
* Use this annotation on a getter method to override the Bean name
|
||||
* parser for Bean -> JSONObject mapping. If this annotation is
|
||||
* present at any level in the class hierarchy, then the method will
|
||||
* not be serialized from the bean into the JSONObject.
|
||||
*/
|
||||
public @interface JSONPropertyIgnore { }
|
||||
47
JSONPropertyName.java
Normal file
47
JSONPropertyName.java
Normal file
@@ -0,0 +1,47 @@
|
||||
package org.json;
|
||||
|
||||
/*
|
||||
Copyright (c) 2018 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 static java.lang.annotation.ElementType.METHOD;
|
||||
import static java.lang.annotation.RetentionPolicy.RUNTIME;
|
||||
|
||||
import java.lang.annotation.Documented;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
@Documented
|
||||
@Retention(RUNTIME)
|
||||
@Target({METHOD})
|
||||
/**
|
||||
* Use this annotation on a getter method to override the Bean name
|
||||
* parser for Bean -> JSONObject mapping. A value set to empty string <code>""</code>
|
||||
* will have the Bean parser fall back to the default field name processing.
|
||||
*/
|
||||
public @interface JSONPropertyName {
|
||||
/**
|
||||
* @return The name of the property as to be used in the JSON Object.
|
||||
*/
|
||||
String value();
|
||||
}
|
||||
@@ -448,7 +448,9 @@ public class JSONTokener {
|
||||
sb.append(c);
|
||||
c = this.next();
|
||||
}
|
||||
this.back();
|
||||
if (!this.eof) {
|
||||
this.back();
|
||||
}
|
||||
|
||||
string = sb.toString().trim();
|
||||
if ("".equals(string)) {
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
package org.json;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.math.BigDecimal;
|
||||
import java.util.Collection;
|
||||
import java.util.Map;
|
||||
|
||||
@@ -326,31 +325,27 @@ public class JSONWriter {
|
||||
return "null";
|
||||
}
|
||||
if (value instanceof JSONString) {
|
||||
Object object;
|
||||
String object;
|
||||
try {
|
||||
object = ((JSONString) value).toJSONString();
|
||||
} catch (Exception e) {
|
||||
throw new JSONException(e);
|
||||
}
|
||||
if (object instanceof String) {
|
||||
return (String) object;
|
||||
if (object != null) {
|
||||
return 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 = JSONObject.numberToString((Number) value);
|
||||
try {
|
||||
// Use the BigDecimal constructor for it's parser to validate the format.
|
||||
@SuppressWarnings("unused")
|
||||
BigDecimal unused = new BigDecimal(numberAsString);
|
||||
if(JSONObject.NUMBER_PATTERN.matcher(numberAsString).matches()) {
|
||||
// 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 JSONObject.quote(numberAsString);
|
||||
}
|
||||
// The Number value is not a valid JSON number.
|
||||
// Instead we will quote it as a string
|
||||
return JSONObject.quote(numberAsString);
|
||||
}
|
||||
if (value instanceof Boolean || value instanceof JSONObject
|
||||
|| value instanceof JSONArray) {
|
||||
@@ -391,7 +386,7 @@ public class JSONWriter {
|
||||
* @throws JSONException If the number is not finite.
|
||||
*/
|
||||
public JSONWriter value(double d) throws JSONException {
|
||||
return this.value(new Double(d));
|
||||
return this.value(Double.valueOf(d));
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
22
README.md
22
README.md
@@ -3,6 +3,8 @@ JSON in Java [package org.json]
|
||||
|
||||
[](https://mvnrepository.com/artifact/org.json/json)
|
||||
|
||||
**[Click here if you just want the latest release jar file.](http://central.maven.org/maven2/org/json/json/20180813/json-20180813.jar)**
|
||||
|
||||
JSON is a light-weight, language independent, data interchange format.
|
||||
See http://www.JSON.org/
|
||||
|
||||
@@ -40,6 +42,18 @@ by this package.
|
||||
JSON Pointers both in the form of string representation and URI fragment
|
||||
representation.
|
||||
|
||||
**JSONPropertyIgnore.java**: Annotation class that can be used on Java Bean getter methods.
|
||||
When used on a bean method that would normally be serialized into a `JSONObject`, it
|
||||
overrides the getter-to-key-name logic and forces the property to be excluded from the
|
||||
resulting `JSONObject`.
|
||||
|
||||
**JSONPropertyName.java**: Annotation class that can be used on Java Bean getter methods.
|
||||
When used on a bean method that would normally be serialized into a `JSONObject`, it
|
||||
overrides the getter-to-key-name logic and uses the value of the annotation. The Bean
|
||||
processor will look through the class hierarchy. This means you can use the annotation on
|
||||
a base class or interface and the value of the annotation will be used even if the getter
|
||||
is overridden in a child class.
|
||||
|
||||
**JSONString.java**: The `JSONString` interface requires a `toJSONString` method,
|
||||
allowing an object to provide its own serialization.
|
||||
|
||||
@@ -74,7 +88,7 @@ https://github.com/stleary/JSON-Java-unit-test
|
||||
|
||||
Numeric types in this package comply with
|
||||
[ECMA-404: The JSON Data Interchange Format](http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-404.pdf) and
|
||||
[RFC 7159: The JavaScript Object Notation (JSON) Data Interchange Format](https://tools.ietf.org/html/rfc7159#section-6).
|
||||
[RFC 8259: The JavaScript Object Notation (JSON) Data Interchange Format](https://tools.ietf.org/html/rfc8259#section-6).
|
||||
This package fully supports `Integer`, `Long`, and `Double` Java types. Partial support
|
||||
for `BigInteger` and `BigDecimal` values in `JSONObject` and `JSONArray` objects is provided
|
||||
in the form of `get()`, `opt()`, and `put()` API methods.
|
||||
@@ -82,7 +96,7 @@ in the form of `get()`, `opt()`, and `put()` API methods.
|
||||
Although 1.6 compatibility is currently supported, it is not a project goal and may be
|
||||
removed in some future release.
|
||||
|
||||
In compliance with RFC7159 page 10 section 9, the parser is more lax with what is valid
|
||||
In compliance with RFC8259 page 10 section 9, the parser is more lax with what is valid
|
||||
JSON than the Generator. For Example, the tab character (U+0009) is allowed when reading
|
||||
JSON Text strings, but when output by the Generator, tab is properly converted to \t in
|
||||
the string. Other instances may occur where reading invalid JSON text does not cause an
|
||||
@@ -93,6 +107,8 @@ invalid number formats (1.2e6.3) will cause errors as such documents can not be
|
||||
Release history:
|
||||
|
||||
~~~
|
||||
20180813 POM change to include Automatic-Module-Name (#431)
|
||||
|
||||
20180130 Recent commits
|
||||
|
||||
20171018 Checkpoint for recent commits.
|
||||
@@ -119,4 +135,4 @@ as of 29 July, 2015.
|
||||
|
||||
JSON-java releases can be found by searching the Maven repository for groupId "org.json"
|
||||
and artifactId "json". For example:
|
||||
https://search.maven.org/#search%7Cgav%7C1%7Cg%3A%22org.json%22%20AND%20a%3A%22json%22
|
||||
https://search.maven.org/search?q=g:org.json%20AND%20a:json&core=gav
|
||||
|
||||
223
XML.java
223
XML.java
@@ -24,17 +24,20 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
*/
|
||||
|
||||
import java.io.Reader;
|
||||
import java.io.StringReader;
|
||||
import java.util.Iterator;
|
||||
|
||||
/**
|
||||
* This provides static methods to convert an XML text into a JSONObject, and to
|
||||
* covert a JSONObject into an XML text.
|
||||
*
|
||||
*
|
||||
* @author JSON.org
|
||||
* @version 2016-08-10
|
||||
*/
|
||||
@SuppressWarnings("boxing")
|
||||
public class XML {
|
||||
|
||||
/** The Character '&'. */
|
||||
public static final Character AMP = '&';
|
||||
|
||||
@@ -61,7 +64,12 @@ public class XML {
|
||||
|
||||
/** The Character '/'. */
|
||||
public static final Character SLASH = '/';
|
||||
|
||||
|
||||
/**
|
||||
* Null attrubute name
|
||||
*/
|
||||
public static final String NULL_ATTR = "xsi:nil";
|
||||
|
||||
/**
|
||||
* Creates an iterator for navigating Code Points in a string instead of
|
||||
* characters. Once Java7 support is dropped, this can be replaced with
|
||||
@@ -69,7 +77,7 @@ public class XML {
|
||||
* string.codePoints()
|
||||
* </code>
|
||||
* which is available in Java8 and above.
|
||||
*
|
||||
*
|
||||
* @see <a href=
|
||||
* "http://stackoverflow.com/a/21791059/6030888">http://stackoverflow.com/a/21791059/6030888</a>
|
||||
*/
|
||||
@@ -104,7 +112,7 @@ public class XML {
|
||||
|
||||
/**
|
||||
* Replace special characters with XML escapes:
|
||||
*
|
||||
*
|
||||
* <pre>
|
||||
* & <small>(ampersand)</small> is replaced by &amp;
|
||||
* < <small>(less than)</small> is replaced by &lt;
|
||||
@@ -112,7 +120,7 @@ public class XML {
|
||||
* " <small>(double quote)</small> is replaced by &quot;
|
||||
* ' <small>(single quote / apostrophe)</small> is replaced by &apos;
|
||||
* </pre>
|
||||
*
|
||||
*
|
||||
* @param string
|
||||
* The string to be escaped.
|
||||
* @return The escaped string.
|
||||
@@ -148,17 +156,17 @@ public class XML {
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param cp code point to test
|
||||
* @return true if the code point is not valid for an XML
|
||||
*/
|
||||
private static boolean mustEscape(int cp) {
|
||||
/* Valid range from https://www.w3.org/TR/REC-xml/#charsets
|
||||
*
|
||||
* #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] | [#x10000-#x10FFFF]
|
||||
*
|
||||
* any Unicode character, excluding the surrogate blocks, FFFE, and FFFF.
|
||||
*
|
||||
* #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] | [#x10000-#x10FFFF]
|
||||
*
|
||||
* any Unicode character, excluding the surrogate blocks, FFFE, and FFFF.
|
||||
*/
|
||||
// isISOControl is true when (cp >= 0 && cp <= 0x1F) || (cp >= 0x7F && cp <= 0x9F)
|
||||
// all ISO control characters are out of range except tabs and new lines
|
||||
@@ -177,7 +185,7 @@ public class XML {
|
||||
|
||||
/**
|
||||
* Removes XML escapes from the string.
|
||||
*
|
||||
*
|
||||
* @param string
|
||||
* string to remove escapes from
|
||||
* @return string with converted entities
|
||||
@@ -209,7 +217,7 @@ public class XML {
|
||||
/**
|
||||
* Throw an exception if the string contains whitespace. Whitespace is not
|
||||
* allowed in tagNames and attributes.
|
||||
*
|
||||
*
|
||||
* @param string
|
||||
* A string.
|
||||
* @throws JSONException Thrown if the string contains whitespace or is empty.
|
||||
@@ -229,7 +237,7 @@ public class XML {
|
||||
|
||||
/**
|
||||
* Scan the content following the named tag, attaching it to the context.
|
||||
*
|
||||
*
|
||||
* @param x
|
||||
* The XMLTokener containing the source string.
|
||||
* @param context
|
||||
@@ -239,7 +247,7 @@ public class XML {
|
||||
* @return true if the close tag is processed.
|
||||
* @throws JSONException
|
||||
*/
|
||||
private static boolean parse(XMLTokener x, JSONObject context, String name, boolean keepStrings)
|
||||
private static boolean parse(XMLTokener x, JSONObject context, String name, XMLParserConfiguration config)
|
||||
throws JSONException {
|
||||
char c;
|
||||
int i;
|
||||
@@ -276,7 +284,7 @@ public class XML {
|
||||
if (x.next() == '[') {
|
||||
string = x.nextCDATA();
|
||||
if (string.length() > 0) {
|
||||
context.accumulate("content", string);
|
||||
context.accumulate(config.cDataTagName, string);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
@@ -325,6 +333,7 @@ public class XML {
|
||||
tagName = (String) token;
|
||||
token = null;
|
||||
jsonobject = new JSONObject();
|
||||
boolean nilAttributeFound = false;
|
||||
for (;;) {
|
||||
if (token == null) {
|
||||
token = x.nextToken();
|
||||
@@ -338,8 +347,17 @@ public class XML {
|
||||
if (!(token instanceof String)) {
|
||||
throw x.syntaxError("Missing value");
|
||||
}
|
||||
jsonobject.accumulate(string,
|
||||
keepStrings ? ((String)token) : stringToValue((String) token));
|
||||
|
||||
if (config.convertNilAttributeToNull
|
||||
&& NULL_ATTR.equals(string)
|
||||
&& Boolean.parseBoolean((String) token)) {
|
||||
nilAttributeFound = true;
|
||||
} else if (!nilAttributeFound) {
|
||||
jsonobject.accumulate(string,
|
||||
config.keepStrings
|
||||
? ((String) token)
|
||||
: stringToValue((String) token));
|
||||
}
|
||||
token = null;
|
||||
} else {
|
||||
jsonobject.accumulate(string, "");
|
||||
@@ -351,7 +369,9 @@ public class XML {
|
||||
if (x.nextToken() != GT) {
|
||||
throw x.syntaxError("Misshaped tag");
|
||||
}
|
||||
if (jsonobject.length() > 0) {
|
||||
if (nilAttributeFound) {
|
||||
context.accumulate(tagName, JSONObject.NULL);
|
||||
} else if (jsonobject.length() > 0) {
|
||||
context.accumulate(tagName, jsonobject);
|
||||
} else {
|
||||
context.accumulate(tagName, "");
|
||||
@@ -370,19 +390,19 @@ public class XML {
|
||||
} else if (token instanceof String) {
|
||||
string = (String) token;
|
||||
if (string.length() > 0) {
|
||||
jsonobject.accumulate("content",
|
||||
keepStrings ? string : stringToValue(string));
|
||||
jsonobject.accumulate(config.cDataTagName,
|
||||
config.keepStrings ? string : stringToValue(string));
|
||||
}
|
||||
|
||||
} else if (token == LT) {
|
||||
// Nested element
|
||||
if (parse(x, jsonobject, tagName,keepStrings)) {
|
||||
if (parse(x, jsonobject, tagName, config)) {
|
||||
if (jsonobject.length() == 0) {
|
||||
context.accumulate(tagName, "");
|
||||
} else if (jsonobject.length() == 1
|
||||
&& jsonobject.opt("content") != null) {
|
||||
&& jsonobject.opt(config.cDataTagName) != null) {
|
||||
context.accumulate(tagName,
|
||||
jsonobject.opt("content"));
|
||||
jsonobject.opt(config.cDataTagName));
|
||||
} else {
|
||||
context.accumulate(tagName, jsonobject);
|
||||
}
|
||||
@@ -396,10 +416,10 @@ public class XML {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* This method is the same as {@link JSONObject#stringToValue(String)}.
|
||||
*
|
||||
*
|
||||
* @param string String to convert
|
||||
* @return JSON value of this string or the string
|
||||
*/
|
||||
@@ -460,16 +480,92 @@ public class XML {
|
||||
* elements are represented as JSONArrays. Content text may be placed in a
|
||||
* "content" member. Comments, prologs, DTDs, and <code><[ [ ]]></code>
|
||||
* are ignored.
|
||||
*
|
||||
*
|
||||
* @param string
|
||||
* The source string.
|
||||
* @return A JSONObject containing the structured data from the XML string.
|
||||
* @throws JSONException Thrown if there is an errors while parsing the string
|
||||
*/
|
||||
public static JSONObject toJSONObject(String string) throws JSONException {
|
||||
return toJSONObject(string, false);
|
||||
return toJSONObject(string, XMLParserConfiguration.ORIGINAL);
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert a well-formed (but not necessarily valid) XML into a
|
||||
* JSONObject. Some information may be lost in this transformation because
|
||||
* JSON is a data format and XML is a document format. XML uses elements,
|
||||
* attributes, and content text, while JSON uses unordered collections of
|
||||
* name/value pairs and arrays of values. JSON does not does not like to
|
||||
* distinguish between elements and attributes. Sequences of similar
|
||||
* elements are represented as JSONArrays. Content text may be placed in a
|
||||
* "content" member. Comments, prologs, DTDs, and <code><[ [ ]]></code>
|
||||
* are ignored.
|
||||
*
|
||||
* @param reader The XML source reader.
|
||||
* @return A JSONObject containing the structured data from the XML string.
|
||||
* @throws JSONException Thrown if there is an errors while parsing the string
|
||||
*/
|
||||
public static JSONObject toJSONObject(Reader reader) throws JSONException {
|
||||
return toJSONObject(reader, XMLParserConfiguration.ORIGINAL);
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert a well-formed (but not necessarily valid) XML into a
|
||||
* JSONObject. Some information may be lost in this transformation because
|
||||
* JSON is a data format and XML is a document format. XML uses elements,
|
||||
* attributes, and content text, while JSON uses unordered collections of
|
||||
* name/value pairs and arrays of values. JSON does not does not like to
|
||||
* distinguish between elements and attributes. Sequences of similar
|
||||
* elements are represented as JSONArrays. Content text may be placed in a
|
||||
* "content" member. Comments, prologs, DTDs, and <code><[ [ ]]></code>
|
||||
* are ignored.
|
||||
*
|
||||
* All values are converted as strings, for 1, 01, 29.0 will not be coerced to
|
||||
* numbers but will instead be the exact value as seen in the XML document.
|
||||
*
|
||||
* @param reader The XML source reader.
|
||||
* @param keepStrings If true, then values will not be coerced into boolean
|
||||
* or numeric values and will instead be left as strings
|
||||
* @return A JSONObject containing the structured data from the XML string.
|
||||
* @throws JSONException Thrown if there is an errors while parsing the string
|
||||
*/
|
||||
public static JSONObject toJSONObject(Reader reader, boolean keepStrings) throws JSONException {
|
||||
if(keepStrings) {
|
||||
return toJSONObject(reader, XMLParserConfiguration.KEEP_STRINGS);
|
||||
}
|
||||
return toJSONObject(reader, XMLParserConfiguration.ORIGINAL);
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert a well-formed (but not necessarily valid) XML into a
|
||||
* JSONObject. Some information may be lost in this transformation because
|
||||
* JSON is a data format and XML is a document format. XML uses elements,
|
||||
* attributes, and content text, while JSON uses unordered collections of
|
||||
* name/value pairs and arrays of values. JSON does not does not like to
|
||||
* distinguish between elements and attributes. Sequences of similar
|
||||
* elements are represented as JSONArrays. Content text may be placed in a
|
||||
* "content" member. Comments, prologs, DTDs, and <code><[ [ ]]></code>
|
||||
* are ignored.
|
||||
*
|
||||
* All values are converted as strings, for 1, 01, 29.0 will not be coerced to
|
||||
* numbers but will instead be the exact value as seen in the XML document.
|
||||
*
|
||||
* @param reader The XML source reader.
|
||||
* @param config Configuration options for the parser
|
||||
* @return A JSONObject containing the structured data from the XML string.
|
||||
* @throws JSONException Thrown if there is an errors while parsing the string
|
||||
*/
|
||||
public static JSONObject toJSONObject(Reader reader, XMLParserConfiguration config) throws JSONException {
|
||||
JSONObject jo = new JSONObject();
|
||||
XMLTokener x = new XMLTokener(reader);
|
||||
while (x.more()) {
|
||||
x.skipPast("<");
|
||||
if(x.more()) {
|
||||
parse(x, jo, null, config);
|
||||
}
|
||||
}
|
||||
return jo;
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert a well-formed (but not necessarily valid) XML string into a
|
||||
@@ -481,10 +577,10 @@ public class XML {
|
||||
* elements are represented as JSONArrays. Content text may be placed in a
|
||||
* "content" member. Comments, prologs, DTDs, and <code><[ [ ]]></code>
|
||||
* are ignored.
|
||||
*
|
||||
*
|
||||
* All values are converted as strings, for 1, 01, 29.0 will not be coerced to
|
||||
* numbers but will instead be the exact value as seen in the XML document.
|
||||
*
|
||||
*
|
||||
* @param string
|
||||
* The source string.
|
||||
* @param keepStrings If true, then values will not be coerced into boolean
|
||||
@@ -493,31 +589,48 @@ public class XML {
|
||||
* @throws JSONException Thrown if there is an errors while parsing the string
|
||||
*/
|
||||
public static JSONObject toJSONObject(String string, boolean keepStrings) throws JSONException {
|
||||
JSONObject jo = new JSONObject();
|
||||
XMLTokener x = new XMLTokener(string);
|
||||
while (x.more()) {
|
||||
x.skipPast("<");
|
||||
if(x.more()) {
|
||||
parse(x, jo, null, keepStrings);
|
||||
}
|
||||
}
|
||||
return jo;
|
||||
return toJSONObject(new StringReader(string), keepStrings);
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert a well-formed (but not necessarily valid) XML string into a
|
||||
* JSONObject. Some information may be lost in this transformation because
|
||||
* JSON is a data format and XML is a document format. XML uses elements,
|
||||
* attributes, and content text, while JSON uses unordered collections of
|
||||
* name/value pairs and arrays of values. JSON does not does not like to
|
||||
* distinguish between elements and attributes. Sequences of similar
|
||||
* elements are represented as JSONArrays. Content text may be placed in a
|
||||
* "content" member. Comments, prologs, DTDs, and <code><[ [ ]]></code>
|
||||
* are ignored.
|
||||
*
|
||||
* All values are converted as strings, for 1, 01, 29.0 will not be coerced to
|
||||
* numbers but will instead be the exact value as seen in the XML document.
|
||||
*
|
||||
* @param string
|
||||
* The source string.
|
||||
* @param config Configuration options for the parser.
|
||||
* @return A JSONObject containing the structured data from the XML string.
|
||||
* @throws JSONException Thrown if there is an errors while parsing the string
|
||||
*/
|
||||
public static JSONObject toJSONObject(String string, XMLParserConfiguration config) throws JSONException {
|
||||
return toJSONObject(new StringReader(string), config);
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert a JSONObject into a well-formed, element-normal XML string.
|
||||
*
|
||||
*
|
||||
* @param object
|
||||
* A JSONObject.
|
||||
* @return A string.
|
||||
* @throws JSONException Thrown if there is an error parsing the string
|
||||
*/
|
||||
public static String toString(Object object) throws JSONException {
|
||||
return toString(object, null);
|
||||
return toString(object, null, XMLParserConfiguration.ORIGINAL);
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert a JSONObject into a well-formed, element-normal XML string.
|
||||
*
|
||||
*
|
||||
* @param object
|
||||
* A JSONObject.
|
||||
* @param tagName
|
||||
@@ -525,7 +638,23 @@ public class XML {
|
||||
* @return A string.
|
||||
* @throws JSONException Thrown if there is an error parsing the string
|
||||
*/
|
||||
public static String toString(final Object object, final String tagName)
|
||||
public static String toString(final Object object, final String tagName) {
|
||||
return toString(object, tagName, XMLParserConfiguration.ORIGINAL);
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert a JSONObject into a well-formed, element-normal XML string.
|
||||
*
|
||||
* @param object
|
||||
* A JSONObject.
|
||||
* @param tagName
|
||||
* The optional name of the enclosing tag.
|
||||
* @param config
|
||||
* Configuration that can control output to XML.
|
||||
* @return A string.
|
||||
* @throws JSONException Thrown if there is an error parsing the string
|
||||
*/
|
||||
public static String toString(final Object object, final String tagName, final XMLParserConfiguration config)
|
||||
throws JSONException {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
JSONArray ja;
|
||||
@@ -553,7 +682,7 @@ public class XML {
|
||||
}
|
||||
|
||||
// Emit content in body
|
||||
if ("content".equals(key)) {
|
||||
if (key.equals(config.cDataTagName)) {
|
||||
if (value instanceof JSONArray) {
|
||||
ja = (JSONArray) value;
|
||||
int jaLength = ja.length();
|
||||
@@ -581,12 +710,12 @@ public class XML {
|
||||
sb.append('<');
|
||||
sb.append(key);
|
||||
sb.append('>');
|
||||
sb.append(toString(val));
|
||||
sb.append(toString(val, null, config));
|
||||
sb.append("</");
|
||||
sb.append(key);
|
||||
sb.append('>');
|
||||
} else {
|
||||
sb.append(toString(val, key));
|
||||
sb.append(toString(val, key, config));
|
||||
}
|
||||
}
|
||||
} else if ("".equals(value)) {
|
||||
@@ -597,7 +726,7 @@ public class XML {
|
||||
// Emit a new tag <k>
|
||||
|
||||
} else {
|
||||
sb.append(toString(value, key));
|
||||
sb.append(toString(value, key, config));
|
||||
}
|
||||
}
|
||||
if (tagName != null) {
|
||||
@@ -624,7 +753,7 @@ public class XML {
|
||||
// XML does not have good support for arrays. If an array
|
||||
// appears in a place where XML is lacking, synthesize an
|
||||
// <array> element.
|
||||
sb.append(toString(val, tagName == null ? "array" : tagName));
|
||||
sb.append(toString(val, tagName == null ? "array" : tagName, config));
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
107
XMLParserConfiguration.java
Normal file
107
XMLParserConfiguration.java
Normal file
@@ -0,0 +1,107 @@
|
||||
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.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Configuration object for the XML parser.
|
||||
* @author AylwardJ
|
||||
*
|
||||
*/
|
||||
public class XMLParserConfiguration {
|
||||
/** Original Configuration of the XML Parser. */
|
||||
public static final XMLParserConfiguration ORIGINAL = new XMLParserConfiguration();
|
||||
/** Original configuration of the XML Parser except that values are kept as strings. */
|
||||
public static final XMLParserConfiguration KEEP_STRINGS = new XMLParserConfiguration(true);
|
||||
/**
|
||||
* When parsing the XML into JSON, specifies if values should be kept as strings (true), or if
|
||||
* they should try to be guessed into JSON values (numeric, boolean, string)
|
||||
*/
|
||||
public final boolean keepStrings;
|
||||
/**
|
||||
* The name of the key in a JSON Object that indicates a CDATA section. Historically this has
|
||||
* been the value "content" but can be changed. Use <code>null</code> to indicate no CDATA
|
||||
* processing.
|
||||
*/
|
||||
public final String cDataTagName;
|
||||
/**
|
||||
* When parsing the XML into JSON, specifies if values with attribute xsi:nil="true"
|
||||
* should be kept as attribute(false), or they should be converted to null(true)
|
||||
*/
|
||||
public final boolean convertNilAttributeToNull;
|
||||
|
||||
/**
|
||||
* Default parser configuration. Does not keep strings, and the CDATA Tag Name is "content".
|
||||
*/
|
||||
public XMLParserConfiguration () {
|
||||
this(false, "content", false);
|
||||
}
|
||||
|
||||
/**
|
||||
* Configure the parser string processing and use the default CDATA Tag Name as "content".
|
||||
* @param keepStrings <code>true</code> to parse all values as string.
|
||||
* <code>false</code> to try and convert XML string values into a JSON value.
|
||||
*/
|
||||
public XMLParserConfiguration (final boolean keepStrings) {
|
||||
this(keepStrings, "content", false);
|
||||
}
|
||||
|
||||
/**
|
||||
* Configure the parser string processing to try and convert XML values to JSON values and
|
||||
* use the passed CDATA Tag Name the processing value. Pass <code>null</code> to
|
||||
* disable CDATA processing
|
||||
* @param cDataTagName<code>null</code> to disable CDATA processing. Any other value
|
||||
* to use that value as the JSONObject key name to process as CDATA.
|
||||
*/
|
||||
public XMLParserConfiguration (final String cDataTagName) {
|
||||
this(false, cDataTagName, false);
|
||||
}
|
||||
|
||||
/**
|
||||
* Configure the parser to use custom settings.
|
||||
* @param keepStrings <code>true</code> to parse all values as string.
|
||||
* <code>false</code> to try and convert XML string values into a JSON value.
|
||||
* @param cDataTagName<code>null</code> to disable CDATA processing. Any other value
|
||||
* to use that value as the JSONObject key name to process as CDATA.
|
||||
*/
|
||||
public XMLParserConfiguration (final boolean keepStrings, final String cDataTagName) {
|
||||
this.keepStrings = keepStrings;
|
||||
this.cDataTagName = cDataTagName;
|
||||
this.convertNilAttributeToNull = false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Configure the parser to use custom settings.
|
||||
* @param keepStrings <code>true</code> to parse all values as string.
|
||||
* <code>false</code> to try and convert XML string values into a JSON value.
|
||||
* @param cDataTagName <code>null</code> to disable CDATA processing. Any other value
|
||||
* to use that value as the JSONObject key name to process as CDATA.
|
||||
* @param convertNilAttributeToNull <code>true</code> to parse values with attribute xsi:nil="true" as null.
|
||||
* <code>false</code> to parse values with attribute xsi:nil="true" as {"xsi:nil":true}.
|
||||
*/
|
||||
public XMLParserConfiguration (final boolean keepStrings, final String cDataTagName, final boolean convertNilAttributeToNull) {
|
||||
this.keepStrings = keepStrings;
|
||||
this.cDataTagName = cDataTagName;
|
||||
this.convertNilAttributeToNull = convertNilAttributeToNull;
|
||||
}
|
||||
}
|
||||
@@ -24,6 +24,8 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
*/
|
||||
|
||||
import java.io.Reader;
|
||||
|
||||
/**
|
||||
* The XMLTokener extends the JSONTokener to provide additional methods
|
||||
* for the parsing of XML texts.
|
||||
@@ -47,6 +49,14 @@ public class XMLTokener extends JSONTokener {
|
||||
entity.put("quot", XML.QUOT);
|
||||
}
|
||||
|
||||
/**
|
||||
* Construct an XMLTokener from a Reader.
|
||||
* @param r A source reader.
|
||||
*/
|
||||
public XMLTokener(Reader r) {
|
||||
super(r);
|
||||
}
|
||||
|
||||
/**
|
||||
* Construct an XMLTokener from a string.
|
||||
* @param s A source string.
|
||||
@@ -125,7 +135,7 @@ public class XMLTokener extends JSONTokener {
|
||||
* @return A Character or an entity String if the entity is not recognized.
|
||||
* @throws JSONException If missing ';' in XML entity.
|
||||
*/
|
||||
public Object nextEntity(char ampersand) throws JSONException {
|
||||
public Object nextEntity(@SuppressWarnings("unused") char ampersand) throws JSONException {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
for (;;) {
|
||||
char c = next();
|
||||
|
||||
Reference in New Issue
Block a user