18 Commits

Author SHA1 Message Date
Sean Leary
37f5bf28e9 Update README.md 2018-08-13 20:46:20 -05:00
Sean Leary
7a17ae0b3e Merge pull request #421 from strkkk/add-emptiness-methods
add isEmpty and isNotEmpty methods
2018-05-26 09:56:23 -05:00
Andrei Paikin
7cad4c3b26 partially revert changes 2018-05-25 22:17:03 +03:00
Andrei_Paikin
05074386d3 change length comparison to isEmpty method 2018-05-21 16:58:13 +03:00
Andrei Paikin
a490ebdb78 add isEmpty and isNotEmpty methods 2018-05-19 09:42:21 +03:00
Sean Leary
3c1535d724 Merge pull request #417 from stleary/fix-double-ctor
fix double ctor in JSONWriter
2018-05-16 08:46:01 -05:00
stleary
a6284df9c7 initial commit 2018-05-02 20:28:45 -05:00
Sean Leary
bfb300835f Merge pull request #411 from johnjaylward/JSONPointerTrailingSlash
Fix for invalid processing of trailing / for JSON Pointer
2018-03-27 07:44:48 -05:00
Sean Leary
06e9ad280f Merge pull request #403 from paulpolushkin/idea-fix
ignore Intellij Idea project files
2018-03-19 19:10:29 -05:00
John J. Aylward
2362c930d1 Fixes #410. Invalid processing of trailing / for JSON Pointer 2018-03-19 09:57:06 -04:00
Sean Leary
2a6b5bacc5 Merge pull request #406 from johnjaylward/FixBeanKeyNameing
Adds annotations to customize field names during Bean serialization
2018-03-14 21:18:23 -05:00
John J. Aylward
a509a28ed4 Cleans up the name check a little to be more permissive on what can be tagged with the new JSONPropertyName annotation.
Also updates the javadoc to reflect the new name allowances
2018-03-11 17:22:05 -04:00
Sean Leary
1c1ef5b211 Merge pull request #405 from johnjaylward/FixNPE
Updates javadoc to match actual exceptions thrown.
2018-03-11 15:57:23 -05:00
John J. Aylward
74b9a60f98 Adds annotation to support custom field names during Bean serialization 2018-03-11 16:28:24 -04:00
John J. Aylward
b63b976acb Updates javadoc to match actual exceptions thrown.
Also optimizes some boxing statements and returns.
2018-03-07 12:35:56 -05:00
Pavel Polushkin
97e180444d ignore Intellij Idea project files 2018-02-25 13:08:58 +03:00
Sean Leary
d402a99fd8 Merge pull request #400 from foldvari/master
XML toJSONObject(Reader reader)
2018-02-10 11:09:26 -06:00
György Földvári
7073bc8c47 XML toJSONObject(Readre reader) 2018-02-04 18:43:35 +01:00
10 changed files with 547 additions and 123 deletions

3
.gitignore vendored
View File

@@ -1,3 +1,6 @@
# ignore eclipse project files
.project
.classpath
# ignore Intellij Idea project files
.idea
*.iml

View File

@@ -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
@@ -182,7 +183,7 @@ public class JSONArray implements Iterable<Object> {
* Construct a JSONArray from an array
*
* @throws JSONException
* If not an array.
* If not an array or if an array value is non-finite number.
*/
public JSONArray(Object array) throws JSONException {
this();
@@ -465,11 +466,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));
@@ -953,8 +954,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 +964,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 +976,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 +1005,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 +1016,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 +1026,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 +1043,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 +1066,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 +1079,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 +1096,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 +1133,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 +1150,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 +1165,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 +1190,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()){
return this;
}
if(index == this.length()){
// simple append
this.put(value);
} else {
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()) {
this.put(JSONObject.NULL);
// we don't need to test validity of NULL objects
this.myArrayList.add(JSONObject.NULL);
}
this.put(value);
}
return this;
return this.put(value);
}
/**
@@ -1322,7 +1352,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 +1528,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 myArrayList.isEmpty();
}
}

View File

@@ -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;
@@ -271,6 +272,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 +283,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 +306,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>
* &#64;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>
* &#64;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>
* &#64;JSONPropertyName("FullName")
* &#64;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 +470,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 +501,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);
@@ -764,11 +810,10 @@ public class JSONObject {
* @return An array of field names, or null if there are no names.
*/
public static String[] getNames(JSONObject jo) {
int length = jo.length();
if (length == 0) {
if (jo.isEmpty()) {
return null;
}
return jo.keySet().toArray(new String[length]);
return jo.keySet().toArray(new String[jo.length()]);
}
/**
@@ -856,7 +901,7 @@ 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
@@ -917,6 +962,15 @@ public class JSONObject {
return this.map.size();
}
/**
* Check if JSONObject is empty.
*
* @return true if JSONObject is empty, otherwise false.
*/
public boolean isEmpty() {
return map.isEmpty();
}
/**
* Produce a JSONArray containing the names of the elements of this
* JSONObject.
@@ -1409,8 +1463,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 +1474,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 +1512,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 +1677,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 +1695,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 +1712,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 +1729,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 +1746,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 +1763,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 +1781,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 +1801,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) {
@@ -1631,7 +1834,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 +1855,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;
}
@@ -1753,7 +1956,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;
}
@@ -2032,7 +2235,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 +2333,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

View File

@@ -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("/")) {
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) {

43
JSONPropertyIgnore.java Normal file
View 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 -&gt; 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
View 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 -&gt; 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();
}

View File

@@ -391,7 +391,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));
}
/**

View File

@@ -40,6 +40,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.
@@ -93,6 +105,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.

View File

@@ -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;
import java.io.StringReader;
import java.util.Iterator;
/**
@@ -470,6 +472,56 @@ public class XML {
return toJSONObject(string, false);
}
/**
* 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>&lt;[ [ ]]></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, false);
}
/**
* 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>&lt;[ [ ]]></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 {
JSONObject jo = new JSONObject();
XMLTokener x = new XMLTokener(reader);
while (x.more()) {
x.skipPast("<");
if(x.more()) {
parse(x, jo, null, keepStrings);
}
}
return jo;
}
/**
* Convert a well-formed (but not necessarily valid) XML string into a
@@ -493,16 +545,9 @@ 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 JSONObject into a well-formed, element-normal XML string.
*

View File

@@ -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.