stleary / json-java Goto Github PK
View Code? Open in Web Editor NEWA reference implementation of a JSON package in Java.
Home Page: http://stleary.github.io/JSON-java/index.html
License: Other
A reference implementation of a JSON package in Java.
Home Page: http://stleary.github.io/JSON-java/index.html
License: Other
I was curious if the last two checkins (one to JSONObject and one to JSONML) may of affected 2 of the regression test cases in TestJSONObject & TestJSONML.
Thanks,
Roger V. Beathard
Here is the output from the regression test cases:
se032c-94-144:> java org.junit.runner.JUnitCore org.json.tests.TestSuite
JUnit version 4.8.2
......................................................................................................................E.................................................................................................................E....................................................................................................................................................
Time: 0.224
There were 2 failures:
FAILURES!!!
Tests run: 379, Failures: 2
Hello,
I know that JSON keys are unordered, but this make the transformation from JSON to XML unreliable, especially if you use xsd validation on the result. I suppose that some other formats are affected too.
I think that preserve the insertion order is a good improvement, with little impact on performance.
It should be as easy as replace java.util.HashMap with java.util.LinkedHashMap on JSONObject.
Thank you very much.
Joan
@Test
public void testSerialization() throws Exception {
final String A_DOUBLE = "aDouble";
final String B_DOUBLE = "bDouble";
final double aDouble = 3.0;
final double bDouble = 3.1;
JSONObject object = new JSONObject();
object.put(A_DOUBLE, aDouble);
object.put(B_DOUBLE, bDouble);
assertEquals(aDouble, object.get(A_DOUBLE)); // PASS
assertEquals(bDouble, object.get(B_DOUBLE)); // PASS
String serializedString = object.toString();
JSONObject deserialized = new JSONObject(serializedString);
assertEquals(bDouble, deserialized.get(B_DOUBLE)); // PASS
assertEquals(aDouble, deserialized.get(A_DOUBLE)); // Fail : expected=3.0(double) and actual=3 (int)
}
Could you add the hashCode() and equals() functions to JSONObject and JSONArray? A use case would be if you wanted to quickly analyze a collection of JSONObjects to find duplicates.
Thanks.
Hello, first thanks for the great software :).
I have a simple POJO with the following property:
private SubscriberStatus status;
public SubscriberStatus getStatus() {
return status;
}
public void setStatus(SubscriberStatus status) {
this.status = status;
}
The SubscriberStatus object is an enum like this:
public enum SubscriberStatus {
ACTIVE,
INACTIVE
}
when I try to turn this POJO into a JSONObject, all properties get a correct value except the status property which ends up empty. I'm using the JSONObject constructor like this:
JSONObject obj = new JSONObject(subscriber); // Where subscriber is an instance of my POJO class.
Now the questions:
Thanks for your time.
Hello,
I've noticed that the JSONObject uses a HashMap which, according to the documentation, does not guarantee an internal order. From my understanding this is different from the JSON specification and can make things difficult to work with.
Hi,
I believe XML class needs to consider that, on cases where a Json code like below is sent:
{
"test":
{ "child": null }
}
is currently being converted as:
<test>
<child>null</child>
</test>
rather than:
<test>
<child/>
</test>
And this is due to an if structure made on the line 408 (XML.java). This comparison needs to be overriding by equals() method. Otherwise, it compares by references:
XML.toString(Object object, String tagName) {
...
/*value is type JSONObject*/
value = jo.opt(key);
/*408*/ if (value == null) {
value = "";
}
I suggest something like value.equals(null) and the problem would be fixed.
Regards
I just downloaded the source and ran the Test JUnit tests. I'm not sure the expected text is correct.
Hi
Just wondering if there is going to be a maven release. There is another project which has published to maven but not for 2 years and the naming isn't standard
https://github.com/eskatos/org.json-java/releases
Currently maven is the most popular project build system.
By mavenizing the project, it'll be much easier to maintain, do continuous integration and more.
No "official" version has ever been released, causing several incompatible ones to be used everywhere.
Here's the code for Java version +1.5.
package org.json;
/*
Copyright (c) 2002 JSON.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
The Software shall be used for Good, not Evil.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
import java.io.IOException;
import java.io.Writer;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.lang.reflect.Method;
import java.util.Collection;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Locale;
import java.util.Map;
import java.util.ResourceBundle;
/**
A JSONObject is an unordered collection of name/value pairs. Its
external form is a string wrapped in curly braces with colons between the
names and values, and commas between the values and names. The internal form
is an object having get
and opt
methods for
accessing the values by name, and put
methods for adding or
replacing values by name. The values can be any of these types:
Boolean
, JSONArray
, JSONObject
,
Number
, String
, or the JSONObject.NULL
object. A JSONObject constructor can be used to convert an external form
JSON text into an internal form whose values can be retrieved with the
get
and opt
methods, or to convert values into a
JSON text using the put
and toString
methods.
A get
method returns a value if one can be found, and throws an
exception if one cannot be found. An opt
method returns a
default value instead of throwing an exception, and so is useful for
obtaining optional values.
The generic get()
and opt()
methods return an
object, which you can cast or query for type. There are also typed
get
and opt
methods that do type checking and type
coercion for you. The opt methods differ from the get methods in that they
do not throw. Instead, they return a specified value, such as null.
The put
methods add or replace values in an object. For example,
myString = new JSONObject().put("JSON", "Hello, World!").toString();
produces the string {"JSON": "Hello, World"}
.
The texts produced by the toString
methods strictly conform to
the JSON syntax rules.
The constructors are more forgiving in the texts they will accept:
,
(comma) may appear just
before the closing brace.</li>
'
(single
quote)</small>.</li>
or single quote, and if they do not contain leading or trailing spaces,
and if they do not contain any of these characters:
<code>{ } [ ] / \ : , = ; #</code> and if they do not look like numbers
and if they are not the reserved words <code>true</code>,
<code>false</code>, or <code>null</code>.</li>
=
or =>
as well as
by <code>:</code>.</li>
;
(semicolon) as
well as by <code>,</code> <small>(comma)</small>.</li>
@author JSON.org
@Version 2011-11-24
*/
public class JSONObject {
/**
JSONObject.NULL is equivalent to the value that JavaScript calls null,
whilst Java's null is equivalent to the value that JavaScript calls
undefined.
*/
private static final class Null {
/**
There is only intended to be a single instance of the NULL object,
so the clone method returns itself.
@return NULL.
*/
protected final Object clone() {
return this;
}
/**
A Null object is equal to the null value and to itself.
@param object An object to test for nullness.
@return true if the object parameter is the JSONObject.NULL object
or null.
*/
public boolean equals(Object object) {
return object == null || object == this;
}
/**
/**
/**
NULL
object than to use Java's null
value.JSONObject.NULL.equals(null)
returns true
.JSONObject.NULL.toString()
returns "null"
./**
/**
/**
if (x.nextClean() != '{') {
throw x.syntaxError("A JSONObject text must begin with '{'");
}
for (;;) {
c = x.nextClean();
switch (c) {
case 0:
throw x.syntaxError("A JSONObject text must end with '}'");
case '}':
return;
default:
x.back();
key = x.nextValue().toString();
}
// The key is followed by ':'. We will also tolerate '=' or '=>'.
c = x.nextClean();
if (c == '=') {
if (x.next() != '>') {
x.back();
}
} else if (c != ':') {
throw x.syntaxError("Expected a ':' after a key");
}
this.putOnce(key, x.nextValue());
// Pairs are separated by ','. We will also tolerate ';'.
switch (x.nextClean()) {
case ';':
case ',':
if (x.nextClean() == '}') {
return;
}
x.back();
break;
case '}':
return;
default:
throw x.syntaxError("Expected a ',' or '}'");
}
}
}
/**
* Construct a JSONObject from a Map.
*
* @param map A map object that can be used to initialize the contents of
* the JSONObject.
* @throws JSONException
*/
public JSONObject(Map<String,Object> map) {
this.map = new HashMap<String,Object>();
if (map != null) {
Iterator<Map.Entry<String, Object>> i = map.entrySet().iterator();
while (i.hasNext()) {
Map.Entry<String, Object> e = i.next();
Object value = e.getValue();
if (value != null) {
this.map.put(e.getKey(), wrap(value));
}
}
}
}
/**
* Construct a JSONObject from an Object using bean getters.
* It reflects on all of the public methods of the object.
* For each of the methods with no parameters and a name starting
* with <code>"get"</code> or <code>"is"</code> followed by an uppercase letter,
* the method is invoked, and a key and the value returned from the getter method
* are put into the new JSONObject.
*
* The key is formed by removing the <code>"get"</code> or <code>"is"</code> prefix.
* If the second remaining character is not upper case, then the first
* character is converted to lower case.
*
* For example, if an object has a method named <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>.
*
* @param bean An object that has getter methods that should be used
* to make a JSONObject.
*/
public JSONObject(Object bean) {
this();
this.populateMap(bean);
}
/**
* Construct a JSONObject from an Object, using reflection to find the
* public members. The resulting JSONObject's keys will be the strings
* from the names array, and the values will be the field values associated
* with those keys in the object. If a key is not found or not visible,
* then it will not be copied into the new JSONObject.
* @param object An object that has fields that should be used to make a
* JSONObject.
* @param names An array of strings, the names of the fields to be obtained
* from the object.
*/
public JSONObject(Object object, String names[]) {
this();
Class<?> c = object.getClass();
for (int i = 0; i < names.length; i += 1) {
String name = names[i];
try {
this.putOpt(name, c.getField(name).get(object));
} catch (Exception ignore) {
}
}
}
/**
* Construct a JSONObject from a source JSON text string.
* This is the most commonly used JSONObject constructor.
* @param source A string beginning
* with <code>{</code> <small>(left brace)</small> and ending
* with <code>}</code> <small>(right brace)</small>.
* @exception JSONException If there is a syntax error in the source
* string or a duplicated key.
*/
public JSONObject(String source) throws JSONException {
this(new JSONTokener(source));
}
/**
* Construct a JSONObject from a ResourceBundle.
* @param baseName The ResourceBundle base name.
* @param locale The Locale to load the ResourceBundle for.
* @throws JSONException If any JSONExceptions are detected.
*/
public JSONObject(String baseName, Locale locale) throws JSONException {
this();
ResourceBundle bundle = ResourceBundle.getBundle(
baseName,
locale,
Thread.currentThread().getContextClassLoader());
// Iterate through the keys in the bundle.
Enumeration<String> keys = bundle.getKeys();
while (keys.hasMoreElements()) {
String key = keys.nextElement();
if (key != null) {
// Go through the path, ensuring that there is a nested JSONObject for each
// segment except the last. Add the value using the last segment's name into
// the deepest nested JSONObject.
String[] path = ((String)key).split("\\.");
int last = path.length - 1;
JSONObject target = this;
for (int i = 0; i < last; i += 1) {
String segment = path[i];
JSONObject nextTarget = target.optJSONObject(segment);
if (nextTarget == null) {
nextTarget = new JSONObject();
target.put(segment, nextTarget);
}
target = nextTarget;
}
target.put(path[last], bundle.getString((String)key));
}
}
}
/**
* Accumulate values under a key. It is similar to the put method except
* that if there is already an object stored under the key then a
* JSONArray is stored under the key to hold all of the accumulated values.
* If there is already a JSONArray, then the new value is appended to it.
* In contrast, the put method replaces the previous value.
*
* If only one value is accumulated that is not a JSONArray, then the
* result will be the same as using put. But if multiple values are
* accumulated, then the result will be like append.
* @param key A key string.
* @param value An object to be accumulated under the key.
* @return this.
* @throws JSONException If the value is an invalid number
* or if the key is null.
*/
public JSONObject accumulate(
String key,
Object value
) throws JSONException {
testValidity(value);
Object object = this.opt(key);
if (object == null) {
this.put(key, value instanceof JSONArray
? new JSONArray().put(value)
: value);
} else if (object instanceof JSONArray) {
((JSONArray)object).put(value);
} else {
this.put(key, new JSONArray().put(object).put(value));
}
return this;
}
/**
* Append values to the array under a key. If the key does not exist in the
* JSONObject, then the key is put in the JSONObject with its value being a
* JSONArray containing the value parameter. If the key was already
* associated with a JSONArray, then the value parameter is appended to it.
* @param key A key string.
* @param value An object to be accumulated under the key.
* @return this.
* @throws JSONException If the key is null or if the current value
* associated with the key is not a JSONArray.
*/
public JSONObject append(String key, Object value) throws JSONException {
testValidity(value);
Object object = this.opt(key);
if (object == null) {
this.put(key, new JSONArray().put(value));
} else if (object instanceof JSONArray) {
this.put(key, ((JSONArray)object).put(value));
} else {
throw new JSONException("JSONObject[" + key +
"] is not a JSONArray.");
}
return this;
}
/**
* Produce a string from a double. The string "null" will be returned if
* the number is not finite.
* @param d A double.
* @return A String.
*/
public static String doubleToString(double d) {
if (Double.isInfinite(d) || Double.isNaN(d)) {
return "null";
}
// Shave off trailing zeros and decimal point, if possible.
String string = Double.toString(d);
if (string.indexOf('.') > 0 && string.indexOf('e') < 0 &&
string.indexOf('E') < 0) {
while (string.endsWith("0")) {
string = string.substring(0, string.length() - 1);
}
if (string.endsWith(".")) {
string = string.substring(0, string.length() - 1);
}
}
return string;
}
/**
* Get the value object associated with a key.
*
* @param key A key string.
* @return The object associated with the key.
* @throws JSONException if the key is not found.
*/
public Object get(String key) throws JSONException {
if (key == null) {
throw new JSONException("Null key.");
}
Object object = this.opt(key);
if (object == null) {
throw new JSONException("JSONObject[" + quote(key) +
"] not found.");
}
return object;
}
/**
* Get the boolean value associated with a key.
*
* @param key A key string.
* @return The truth.
* @throws JSONException
* if the value is not a Boolean or the String "true" or "false".
*/
public boolean getBoolean(String key) throws JSONException {
Object object = this.get(key);
if (object.equals(Boolean.FALSE) ||
(object instanceof String &&
((String)object).equalsIgnoreCase("false"))) {
return false;
} else if (object.equals(Boolean.TRUE) ||
(object instanceof String &&
((String)object).equalsIgnoreCase("true"))) {
return true;
}
throw new JSONException("JSONObject[" + quote(key) +
"] is not a Boolean.");
}
/**
* Get the double value associated with a key.
* @param key A key string.
* @return The numeric value.
* @throws JSONException if the key is not found or
* if the value is not a Number object and cannot be converted to a number.
*/
public double getDouble(String key) throws JSONException {
Object object = this.get(key);
try {
return object instanceof Number
? ((Number)object).doubleValue()
: Double.parseDouble((String)object);
} catch (Exception e) {
throw new JSONException("JSONObject[" + quote(key) +
"] is not a number.");
}
}
/**
* Get the int value associated with a key.
*
* @param key A key string.
* @return The integer value.
* @throws JSONException if the key is not found or if the value cannot
* be converted to an integer.
*/
public int getInt(String key) throws JSONException {
Object 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.");
}
}
/**
* Get the JSONArray value associated with a key.
*
* @param key A key string.
* @return A JSONArray which is the value.
* @throws JSONException if the key is not found or
* if the value is not a JSONArray.
*/
public JSONArray getJSONArray(String key) throws JSONException {
Object object = this.get(key);
if (object instanceof JSONArray) {
return (JSONArray)object;
}
throw new JSONException("JSONObject[" + quote(key) +
"] is not a JSONArray.");
}
/**
* Get the JSONObject value associated with a key.
*
* @param key A key string.
* @return A JSONObject which is the value.
* @throws JSONException if the key is not found or
* if the value is not a JSONObject.
*/
public JSONObject getJSONObject(String key) throws JSONException {
Object object = this.get(key);
if (object instanceof JSONObject) {
return (JSONObject)object;
}
throw new JSONException("JSONObject[" + quote(key) +
"] is not a JSONObject.");
}
/**
* Get the long value associated with a key.
*
* @param key A key string.
* @return The long value.
* @throws JSONException if the key is not found or if the value cannot
* be converted to a long.
*/
public long getLong(String key) throws JSONException {
Object 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.");
}
}
/**
* Get an array of field names from a JSONObject.
*
* @return An array of field names, or null if there are no names.
*/
public static String[] getNames(JSONObject jo) {
int length = jo.length();
if (length == 0) {
return null;
}
Iterator<String> iterator = jo.keys();
String[] names = new String[length];
int i = 0;
while (iterator.hasNext()) {
names[i] = iterator.next();
i += 1;
}
return names;
}
/**
* Get an array of field names from an Object.
*
* @return An array of field names, or null if there are no names.
*/
public static String[] getNames(Object object) {
if (object == null) {
return null;
}
Class<?> klass = object.getClass();
Field[] fields = klass.getFields();
int length = fields.length;
if (length == 0) {
return null;
}
String[] names = new String[length];
for (int i = 0; i < length; i += 1) {
names[i] = fields[i].getName();
}
return names;
}
/**
* Get the string associated with a key.
*
* @param key A key string.
* @return A string which is the value.
* @throws JSONException if there is no string value for the key.
*/
public String getString(String key) throws JSONException {
Object object = this.get(key);
if (object instanceof String) {
return (String)object;
}
throw new JSONException("JSONObject[" + quote(key) +
"] not a string.");
}
/**
* Determine if the JSONObject contains a specific key.
* @param key A key string.
* @return true if the key exists in the JSONObject.
*/
public boolean has(String key) {
return this.map.containsKey(key);
}
/**
* Increment a property of a JSONObject. If there is no such property,
* create one with a value of 1. If there is such a property, and if
* it is an Integer, Long, Double, or Float, then add one to it.
* @param key A key string.
* @return this.
* @throws JSONException If there is already a property with this name
* that is not an Integer, Long, Double, or Float.
*/
public JSONObject increment(String key) throws JSONException {
Object value = this.opt(key);
if (value == null) {
this.put(key, 1);
} else if (value instanceof Integer) {
this.put(key, ((Integer)value).intValue() + 1);
} else if (value instanceof Long) {
this.put(key, ((Long)value).longValue() + 1);
} else if (value instanceof Double) {
this.put(key, ((Double)value).doubleValue() + 1);
} else if (value instanceof Float) {
this.put(key, ((Float)value).floatValue() + 1);
} else {
throw new JSONException("Unable to increment [" + quote(key) + "].");
}
return this;
}
/**
* Determine if the value associated with the key is null 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.
*/
public boolean isNull(String key) {
return JSONObject.NULL.equals(this.opt(key));
}
/**
* Get an enumeration of the keys of the JSONObject.
*
* @return An iterator of the keys.
*/
public Iterator<String> keys() {
return this.map.keySet().iterator();
}
/**
* Get the number of keys stored in the JSONObject.
*
* @return The number of keys in the JSONObject.
*/
public int length() {
return this.map.size();
}
/**
* 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.
*/
public JSONArray names() {
JSONArray ja = new JSONArray();
Iterator<String> keys = this.keys();
while (keys.hasNext()) {
ja.put(keys.next());
}
return ja.length() == 0 ? null : ja;
}
/**
* Produce a string from a Number.
* @param number A Number
* @return A String.
* @throws JSONException If n is a non-finite number.
*/
public static String numberToString(Number number)
throws JSONException {
if (number == null) {
throw new JSONException("Null pointer");
}
testValidity(number);
// Shave off trailing zeros and decimal point, if possible.
String string = number.toString();
if (string.indexOf('.') > 0 && string.indexOf('e') < 0 &&
string.indexOf('E') < 0) {
while (string.endsWith("0")) {
string = string.substring(0, string.length() - 1);
}
if (string.endsWith(".")) {
string = string.substring(0, string.length() - 1);
}
}
return string;
}
/**
* Get an optional value associated with a key.
* @param key A key string.
* @return An object which is the value, or null if there is no value.
*/
public Object opt(String key) {
return key == null ? null : this.map.get(key);
}
/**
* Get an optional boolean associated with a key.
* It returns false if there is no such key, or if the value is not
* Boolean.TRUE or the String "true".
*
* @param key A key string.
* @return The truth.
*/
public boolean optBoolean(String key) {
return this.optBoolean(key, false);
}
/**
* Get an optional boolean associated with a key.
* It returns the defaultValue if there is no such key, or if it is not
* a Boolean or the String "true" or "false" (case insensitive).
*
* @param key A key string.
* @param defaultValue The default.
* @return The truth.
*/
public boolean optBoolean(String key, boolean defaultValue) {
try {
return this.getBoolean(key);
} catch (Exception e) {
return defaultValue;
}
}
/**
* Get an optional double associated with a key,
* or NaN 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.
*
* @param key A string which is the key.
* @return An object which is the value.
*/
public double optDouble(String key) {
return this.optDouble(key, Double.NaN);
}
/**
* Get an optional double 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.
*
* @param key A key string.
* @param defaultValue The default.
* @return An object which is the value.
*/
public double optDouble(String key, double defaultValue) {
try {
return this.getDouble(key);
} catch (Exception e) {
return defaultValue;
}
}
/**
* Get an optional int value associated with a key,
* or zero if there is no such key or if the value is not a number.
* If the value is a string, an attempt will be made to evaluate it as
* a number.
*
* @param key A key string.
* @return An object which is the value.
*/
public int optInt(String key) {
return this.optInt(key, 0);
}
/**
* Get an optional int value associated with a key,
* or the default if there is no such key or if the value is not a number.
* If the value is a string, an attempt will be made to evaluate it as
* a number.
*
* @param key A key string.
* @param defaultValue The default.
* @return An object which is the value.
*/
public int optInt(String key, int defaultValue) {
try {
return this.getInt(key);
} catch (Exception e) {
return defaultValue;
}
}
/**
* Get an optional JSONArray associated with a key.
* It returns null if there is no such key, or if its value is not a
* JSONArray.
*
* @param key A key string.
* @return A JSONArray which is the value.
*/
public JSONArray optJSONArray(String key) {
Object o = this.opt(key);
return o instanceof JSONArray ? (JSONArray)o : null;
}
/**
* Get an optional JSONObject associated with a key.
* It returns null if there is no such key, or if its value is not a
* JSONObject.
*
* @param key A key string.
* @return A JSONObject which is the value.
*/
public JSONObject optJSONObject(String key) {
Object object = this.opt(key);
return object instanceof JSONObject ? (JSONObject)object : null;
}
/**
* Get an optional long value associated with a key,
* or zero if there is no such key or if the value is not a number.
* If the value is a string, an attempt will be made to evaluate it as
* a number.
*
* @param key A key string.
* @return An object which is the value.
*/
public long optLong(String key) {
return this.optLong(key, 0);
}
/**
* Get an optional long value associated with a key,
* or the default if there is no such key or if the value is not a number.
* If the value is a string, an attempt will be made to evaluate it as
* a number.
*
* @param key A key string.
* @param defaultValue The default.
* @return An object which is the value.
*/
public long optLong(String key, long defaultValue) {
try {
return this.getLong(key);
} catch (Exception e) {
return defaultValue;
}
}
/**
* Get an optional string associated with a key.
* It returns an empty string if there is no such key. If the value is not
* a string and is not null, then it is converted to a string.
*
* @param key A key string.
* @return A string which is the value.
*/
public String optString(String key) {
return this.optString(key, "");
}
/**
* Get an optional string associated with a key.
* It returns the defaultValue if there is no such key.
*
* @param key A key string.
* @param defaultValue The default.
* @return A string which is the value.
*/
public String optString(String key, String defaultValue) {
Object object = this.opt(key);
return NULL.equals(object) ? defaultValue : object.toString();
}
private void populateMap(Object bean) {
Class<?> klass = bean.getClass();
// If klass is a System class then set includeSuperClass to false.
boolean includeSuperClass = klass.getClassLoader() != null;
Method[] methods = includeSuperClass
? klass.getMethods()
: klass.getDeclaredMethods();
for (int i = 0; i < methods.length; i += 1) {
try {
Method method = methods[i];
if (Modifier.isPublic(method.getModifiers())) {
String name = method.getName();
String key = "";
if (name.startsWith("get")) {
if (name.equals("getClass") ||
name.equals("getDeclaringClass")) {
key = "";
} else {
key = name.substring(3);
}
} else if (name.startsWith("is")) {
key = name.substring(2);
}
if (key.length() > 0 &&
Character.isUpperCase(key.charAt(0)) &&
method.getParameterTypes().length == 0) {
if (key.length() == 1) {
key = key.toLowerCase();
} else if (!Character.isUpperCase(key.charAt(1))) {
key = key.substring(0, 1).toLowerCase() +
key.substring(1);
}
Object result = method.invoke(bean, (Object[])null);
if (result != null) {
this.map.put(key, wrap(result));
}
}
}
} catch (Exception ignore) {
}
}
}
/**
* Put a key/boolean pair in the JSONObject.
*
* @param key A key string.
* @param value A boolean which is the value.
* @return this.
* @throws JSONException If the key is null.
*/
public JSONObject put(String key, boolean value) throws JSONException {
this.put(key, value ? Boolean.TRUE : Boolean.FALSE);
return this;
}
/**
* Put a key/value pair in the JSONObject, where the value will be a
* JSONArray which is produced from a Collection.
* @param key A key string.
* @param value A Collection value.
* @return this.
* @throws JSONException
*/
public JSONObject put(String key, Collection<Object> value) throws JSONException {
this.put(key, new JSONArray(value));
return this;
}
/**
* Put a key/double pair in the JSONObject.
*
* @param key A key string.
* @param value A double which is the value.
* @return this.
* @throws JSONException If the key is null or if the number is invalid.
*/
public JSONObject put(String key, double value) throws JSONException {
this.put(key, new Double(value));
return this;
}
/**
* Put a key/int pair in the JSONObject.
*
* @param key A key string.
* @param value An int which is the value.
* @return this.
* @throws JSONException If the key is null.
*/
public JSONObject put(String key, int value) throws JSONException {
this.put(key, new Integer(value));
return this;
}
/**
* Put a key/long pair in the JSONObject.
*
* @param key A key string.
* @param value A long which is the value.
* @return this.
* @throws JSONException If the key is null.
*/
public JSONObject put(String key, long value) throws JSONException {
this.put(key, new Long(value));
return this;
}
/**
* Put a key/value pair in the JSONObject, where the value will be a
* JSONObject which is produced from a Map.
* @param key A key string.
* @param value A Map value.
* @return this.
* @throws JSONException
*/
public JSONObject put(String key, Map<String,Object> value) throws JSONException {
this.put(key, new JSONObject(value));
return this;
}
/**
* Put a key/value pair in the JSONObject. If the value is null,
* then the key will be removed from the JSONObject if it is present.
* @param key A key string.
* @param value An object which is the value. It should be of one of these
* types: Boolean, Double, Integer, JSONArray, JSONObject, Long, String,
* or the JSONObject.NULL object.
* @return this.
* @throws JSONException If the value is non-finite number
* or if the key is null.
*/
public JSONObject put(String key, Object value) throws JSONException {
if (key == null) {
throw new JSONException("Null key.");
}
if (value != null) {
testValidity(value);
this.map.put(key, value);
} else {
this.remove(key);
}
return this;
}
/**
* Put a key/value pair in the JSONObject, but only if the key and the
* value are both non-null, and only if there is not already a member
* with that name.
* @param key
* @param value
* @return his.
* @throws JSONException if the key is a duplicate
*/
public JSONObject putOnce(String key, Object value) throws JSONException {
if (key != null && value != null) {
if (this.opt(key) != null) {
throw new JSONException("Duplicate key \"" + key + "\"");
}
this.put(key, value);
}
return this;
}
/**
* Put a key/value pair in the JSONObject, but only if the
* key and the value are both non-null.
* @param key A key string.
* @param value An object which is the value. It should be of one of these
* types: Boolean, Double, Integer, JSONArray, JSONObject, Long, String,
* or the JSONObject.NULL object.
* @return this.
* @throws JSONException If the value is a non-finite number.
*/
public JSONObject putOpt(String key, Object value) throws JSONException {
if (key != null && value != null) {
this.put(key, value);
}
return this;
}
/**
* 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.
* @param string A String
* @return A String correctly formatted for insertion in a JSON text.
*/
public static String quote(String string) {
if (string == null || string.length() == 0) {
return "\"\"";
}
char b;
char c = 0;
String hhhh;
int i;
int len = string.length();
StringBuffer sb = new StringBuffer(len + 4);
sb.append('"');
for (i = 0; i < len; i += 1) {
b = c;
c = string.charAt(i);
switch (c) {
case '\\':
case '"':
sb.append('\\');
sb.append(c);
break;
case '/':
if (b == '<') {
sb.append('\\');
}
sb.append(c);
break;
case '\b':
sb.append("\\b");
break;
case '\t':
sb.append("\\t");
break;
case '\n':
sb.append("\\n");
break;
case '\f':
sb.append("\\f");
break;
case '\r':
sb.append("\\r");
break;
default:
if (c < ' ' || (c >= '\u0080' && c < '\u00a0') ||
(c >= '\u2000' && c < '\u2100')) {
hhhh = "000" + Integer.toHexString(c);
sb.append("\\u" + hhhh.substring(hhhh.length() - 4));
} else {
sb.append(c);
}
}
}
sb.append('"');
return sb.toString();
}
/**
* Remove a name and its value, if present.
* @param key The name to be removed.
* @return The value that was associated with the name,
* or null if there was no value.
*/
public Object remove(String key) {
return this.map.remove(key);
}
/**
* Try to convert a string into a number, boolean, or null. If the string
* can't be converted, return the string.
* @param string A String.
* @return A simple JSON value.
*/
public static Object stringToValue(String string) {
Double d;
if (string.equals("")) {
return string;
}
if (string.equalsIgnoreCase("true")) {
return Boolean.TRUE;
}
if (string.equalsIgnoreCase("false")) {
return Boolean.FALSE;
}
if (string.equalsIgnoreCase("null")) {
return JSONObject.NULL;
}
/*
* If it might be a number, try converting it.
* If a number cannot be produced, then the value will just
* be a string. Note that the plus and implied string
* conventions are non-standard. A JSON parser may accept
* non-JSON forms as long as it accepts all correct JSON forms.
*/
char b = string.charAt(0);
if ((b >= '0' && b <= '9') || b == '.' || b == '-' || b == '+') {
try {
if (string.indexOf('.') > -1 ||
string.indexOf('e') > -1 || string.indexOf('E') > -1) {
d = Double.valueOf(string);
if (!d.isInfinite() && !d.isNaN()) {
return d;
}
} else {
Long myLong = new Long(string);
if (myLong.longValue() == myLong.intValue()) {
return new Integer(myLong.intValue());
} else {
return myLong;
}
}
} catch (Exception ignore) {
}
}
return string;
}
/**
* Throw an exception if the object is a NaN or infinite number.
* @param o The object to test.
* @throws JSONException If o is a non-finite number.
*/
public static void testValidity(Object o) throws JSONException {
if (o != null) {
if (o instanceof Double) {
if (((Double)o).isInfinite() || ((Double)o).isNaN()) {
throw new JSONException(
"JSON does not allow non-finite numbers.");
}
} else if (o instanceof Float) {
if (((Float)o).isInfinite() || ((Float)o).isNaN()) {
throw new JSONException(
"JSON does not allow non-finite numbers.");
}
}
}
}
/**
* Produce a JSONArray containing the values of the members of this
* JSONObject.
* @param names A JSONArray containing a list of key strings. This
* determines the sequence of the values in the result.
* @return A JSONArray of values.
* @throws JSONException If any of the values are non-finite numbers.
*/
public JSONArray toJSONArray(JSONArray names) throws JSONException {
if (names == null || names.length() == 0) {
return null;
}
JSONArray ja = new JSONArray();
for (int i = 0; i < names.length(); i += 1) {
ja.put(this.opt(names.getString(i)));
}
return ja;
}
/**
* Make a JSON text of this JSONObject. For compactness, no whitespace
* is added. If this would not result in a syntactically correct JSON text,
* then null will be returned instead.
* <p>
* Warning: This method assumes that the data structure is acyclical.
*
* @return a printable, displayable, portable, transmittable
* representation of the object, beginning
* with <code>{</code> <small>(left brace)</small> and ending
* with <code>}</code> <small>(right brace)</small>.
*/
public String toString() {
try {
Iterator<String> keys = this.keys();
StringBuffer sb = new StringBuffer("{");
while (keys.hasNext()) {
if (sb.length() > 1) {
sb.append(',');
}
Object o = keys.next();
sb.append(quote(o.toString()));
sb.append(':');
sb.append(valueToString(this.map.get(o)));
}
sb.append('}');
return sb.toString();
} catch (Exception e) {
return null;
}
}
/**
* Make a prettyprinted JSON text of this JSONObject.
* <p>
* Warning: This method assumes that the data structure is acyclical.
* @param indentFactor The number of spaces to add to each level of
* indentation.
* @return a printable, displayable, portable, transmittable
* representation of the object, beginning
* with <code>{</code> <small>(left brace)</small> and ending
* with <code>}</code> <small>(right brace)</small>.
* @throws JSONException If the object contains an invalid number.
*/
public String toString(int indentFactor) throws JSONException {
return this.toString(indentFactor, 0);
}
/**
* Make a prettyprinted JSON text of this JSONObject.
* <p>
* Warning: This method assumes that the data structure is acyclical.
* @param indentFactor The number of spaces to add to each level of
* indentation.
* @param indent The indentation of the top level.
* @return a printable, displayable, transmittable
* representation of the object, beginning
* with <code>{</code> <small>(left brace)</small> and ending
* with <code>}</code> <small>(right brace)</small>.
* @throws JSONException If the object contains an invalid number.
*/
String toString(int indentFactor, int indent) throws JSONException {
int i;
int length = this.length();
if (length == 0) {
return "{}";
}
Iterator<String> keys = this.keys();
int newindent = indent + indentFactor;
Object object;
StringBuffer sb = new StringBuffer("{");
if (length == 1) {
object = keys.next();
sb.append(quote(object.toString()));
sb.append(": ");
sb.append(valueToString(this.map.get(object), indentFactor,
indent));
} else {
while (keys.hasNext()) {
object = keys.next();
if (sb.length() > 1) {
sb.append(",\n");
} else {
sb.append('\n');
}
for (i = 0; i < newindent; i += 1) {
sb.append(' ');
}
sb.append(quote(object.toString()));
sb.append(": ");
sb.append(valueToString(this.map.get(object), indentFactor,
newindent));
}
if (sb.length() > 1) {
sb.append('\n');
for (i = 0; i < indent; i += 1) {
sb.append(' ');
}
}
}
sb.append('}');
return sb.toString();
}
/**
* Make a JSON text of an Object value. If the object has an
* value.toJSONString() method, then that method will be used to produce
* the JSON text. The method is required to produce a strictly
* conforming text. If the object does not contain a toJSONString
* method (which is the most common case), then a text will be
* produced by other means. If the value is an array or Collection,
* then a JSONArray will be made from it and its toJSONString method
* will be called. If the value is a MAP, then a JSONObject will be made
* from it and its toJSONString method will be called. Otherwise, the
* value's toString method will be called, and the result will be quoted.
*
* <p>
* Warning: This method assumes that the data structure is acyclical.
* @param value The value to be serialized.
* @return a printable, displayable, transmittable
* representation of the object, beginning
* with <code>{</code> <small>(left brace)</small> and ending
* with <code>}</code> <small>(right brace)</small>.
* @throws JSONException If the value is or contains an invalid number.
*/
@SuppressWarnings("unchecked")
public static String valueToString(Object value) throws JSONException {
if (value == null || value.equals(null)) {
return "null";
}
if (value instanceof JSONString) {
Object object;
try {
object = ((JSONString)value).toJSONString();
} catch (Exception e) {
throw new JSONException(e);
}
if (object instanceof String) {
return (String)object;
}
throw new JSONException("Bad value from toJSONString: " + object);
}
if (value instanceof Number) {
return numberToString((Number) value);
}
if (value instanceof Boolean || value instanceof JSONObject ||
value instanceof JSONArray) {
return value.toString();
}
if (value instanceof Map) {
return new JSONObject((Map<String,Object>)value).toString();
}
if (value instanceof Collection) {
return new JSONArray((Collection<Object>)value).toString();
}
if (value.getClass().isArray()) {
return new JSONArray(value).toString();
}
return quote(value.toString());
}
/**
* Make a prettyprinted JSON text of an object value.
* <p>
* Warning: This method assumes that the data structure is acyclical.
* @param value The value to be serialized.
* @param indentFactor The number of spaces to add to each level of
* indentation.
* @param indent The indentation of the top level.
* @return a printable, displayable, transmittable
* representation of the object, beginning
* with <code>{</code> <small>(left brace)</small> and ending
* with <code>}</code> <small>(right brace)</small>.
* @throws JSONException If the object contains an invalid number.
*/
@SuppressWarnings("unchecked")
static String valueToString(
Object value,
int indentFactor,
int indent
) throws JSONException {
if (value == null || value.equals(null)) {
return "null";
}
try {
if (value instanceof JSONString) {
Object o = ((JSONString)value).toJSONString();
if (o instanceof String) {
return (String)o;
}
}
} catch (Exception ignore) {
}
if (value instanceof Number) {
return numberToString((Number) value);
}
if (value instanceof Boolean) {
return value.toString();
}
if (value instanceof JSONObject) {
return ((JSONObject)value).toString(indentFactor, indent);
}
if (value instanceof JSONArray) {
return ((JSONArray)value).toString(indentFactor, indent);
}
if (value instanceof Map) {
return new JSONObject((Map<String,Object>)value).toString(indentFactor, indent);
}
if (value instanceof Collection) {
return new JSONArray((Collection<Object>)value).toString(indentFactor, indent);
}
if (value.getClass().isArray()) {
return new JSONArray(value).toString(indentFactor, indent);
}
return quote(value.toString());
}
/**
* Wrap an object, if necessary. If the object is null, 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 one of the java packages, turn it into a string. And if
* it doesn't, try to wrap it in a JSONObject. If the wrapping fails,
* then null is returned.
*
* @param object The object to wrap
* @return The wrapped value
*/
@SuppressWarnings("unchecked")
public static Object wrap(Object object) {
try {
if (object == null) {
return NULL;
}
if (object instanceof JSONObject || object instanceof JSONArray ||
NULL.equals(object) || object instanceof JSONString ||
object instanceof Byte || object instanceof Character ||
object instanceof Short || object instanceof Integer ||
object instanceof Long || object instanceof Boolean ||
object instanceof Float || object instanceof Double ||
object instanceof String) {
return object;
}
if (object instanceof Collection) {
return new JSONArray((Collection<Object>)object);
}
if (object.getClass().isArray()) {
return new JSONArray(object);
}
if (object instanceof Map) {
return new JSONObject((Map<String,Object>)object);
}
Package objectPackage = object.getClass().getPackage();
String objectPackageName = objectPackage != null
? objectPackage.getName()
: "";
if (
objectPackageName.startsWith("java.") ||
objectPackageName.startsWith("javax.") ||
object.getClass().getClassLoader() == null
) {
return object.toString();
}
return new JSONObject(object);
} catch(Exception exception) {
return null;
}
}
/**
* Write the contents of the JSONObject as JSON text to a writer.
* For compactness, no whitespace is added.
* <p>
* Warning: This method assumes that the data structure is acyclical.
*
* @return The writer.
* @throws JSONException
*/
public Writer write(Writer writer) throws JSONException {
try {
boolean commanate = false;
Iterator<String> keys = this.keys();
writer.write('{');
while (keys.hasNext()) {
if (commanate) {
writer.write(',');
}
Object key = keys.next();
writer.write(quote(key.toString()));
writer.write(':');
Object value = this.map.get(key);
if (value instanceof JSONObject) {
((JSONObject)value).write(writer);
} else if (value instanceof JSONArray) {
((JSONArray)value).write(writer);
} else {
writer.write(valueToString(value));
}
commanate = true;
}
writer.write('}');
return writer;
} catch (IOException exception) {
throw new JSONException(exception);
}
}
}
package org.json;
/*
Copyright (c) 2002 JSON.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
The Software shall be used for Good, not Evil.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
import java.io.IOException;
import java.io.Writer;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
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
internal form is an object having get
and opt
methods for accessing the values by index, and put
methods for
adding or replacing values. The values can be any of these types:
Boolean
, JSONArray
, JSONObject
,
Number
, String
, or the
JSONObject.NULL object
.
The constructor can convert a JSON text into a Java object. The
toString
method converts to JSON text.
A get
method returns a value if one can be found, and throws an
exception if one cannot be found. An opt
method returns a
default value instead of throwing an exception, and so is useful for
obtaining optional values.
The generic get()
and opt()
methods return an
object which you can cast or query for type. There are also typed
get
and opt
methods that do type checking and type
coercion for you.
The texts produced by the toString
methods strictly conform to
JSON syntax rules. The constructors are more forgiving in the texts they will
accept:
,
(comma) may appear just
before the closing bracket.</li>
null
value will be inserted when there
is <code>,</code> <small>(comma)</small> elision.</li>
'
(single
quote)</small>.</li>
or single quote, and if they do not contain leading or trailing spaces,
and if they do not contain any of these characters:
<code>{ } [ ] / \ : , = ; #</code> and if they do not look like numbers
and if they are not the reserved words <code>true</code>,
<code>false</code>, or <code>null</code>.</li>
;
(semicolon) as
well as by <code>,</code> <small>(comma)</small>.</li>
@author JSON.org
@Version 2011-12-19
*/
public class JSONArray {
/**
/**
/**
/**
[
(left bracket)]
(right bracket)./**
/**
/**
/**
We often find that when catching JSONExceptions, the only sensible way to handle it is to re-throw it as a runtime-exception and let it be handled in the top-level exception handler of our application. Would you be willing to extend RuntimeException instead?
I've played a little bit with the code to improve the performance of toString() methods.
Here is a summary of most important changes:
I've wrote a simple test to measure the performance between changes and here is the results:
D:\develop\json\douglascrockford-JSON-java-d98dc0b>java -cp org.apache.commons.io.jar;. PerfTest
str: 5206
D:\develop\json\douglascrockford-JSON-java-d98dc0b>java -cp org.apache.commons.io.jar;. PerfTest
str: 5241
D:\develop\json\douglascrockford-JSON-java-d98dc0b>java -cp org.apache.commons.io.jar;. PerfTest
str: 5280
D:\develop\json\douglascrockford-JSON-java-d98dc0b>cd ..\new-json
D:\develop\json\new-json>java -cp org.apache.commons.io.jar;. PerfTest
str: 2912
D:\develop\json\new-json>java -cp org.apache.commons.io.jar;. PerfTest
str: 2946
D:\develop\json\new-json>java -cp org.apache.commons.io.jar;. PerfTest
str: 2912
This means that the average milliseconds for the old code is 5242 and 2923 for the new code. This means that the new code is ~1.8 times faster that the original code.
Here is a zip file (http://depositfiles.com/files/vnfv5budt) that includes:
I cannot include the JSON file I've been testing with, but it contains various data types, JSON objects and arrays. It is at about 74K big.
Suggest possible involvement in the JSR-353 related to JSON which is in development.
The JSONObject's map based constructor does not throw an exception when the Map contains null keys.
The following will fail the NotNull check.
HashMap m = new HashMap();
m.put("foo", "bar");
m.put(null, "oops");
JSONObject json = new JSONObject(m);
assertNotNull(json.toString());
assertEquals("{\"foo\":\"bar\"}", json.toString());
And the following will fail the Equals check:
HashMap mFoo = new HashMap();
mFoo.put("one", "two");
mFoo.put(null, "three");
HashMap m = new HashMap();
m.put("foo", mFoo);
JSONObject json = new JSONObject(m);
assertNotNull(json.toString());
assertEquals("{\"foo\":{\"one\":\"two\"}}", json.toString()); // actual is {"foo":null}
I am interested to know if the current behavior is by design or if an exception is meant to be thrown since the javadocs for the constructor says it throws a JSONException
but it doesn't declare that it throws it.
Hi Douglas
The attempt to guess the type of a text node or an attribute value may change the type which may be unintended. If the intended type is a string, "01" is not equal with "1". So operations change values which can cause unwanted effects.
Furthermore the behavior is not consistent: "00" remains unchanged (remains a String) while "01" is converted to the number 1 as you can see in the sample below.
Also automatic conversion to boolean might have unwanted effects. Imagine the title of a book's chapter is "True" - intentionally with upper case "T". As far as I could see currently I am not able to convert this title to Json without implicitly changing it to a boolean and therefore losing information.
Sample:
xml:
<root>
<id>01</id>
<id>1</id>
<id>00</id>
<id>0</id>
<title>True</title>
</root>
code:
println org.json.JSONML.toJSONArray(xml)
output:
["root",["id",1],["id",1],["id","00"],["id",0],["title",true]]
I would suggest to either change this or at least to add an option to control the behavior in a static way. (e.g. adding a non-final static boolean field KEEP_STRINGS which can be set to true)
Best regards,
yaccob
public void testNull() throws Exception {
JSONObject j;
j = new JSONObject("{\"message\":\"null\"}");
assertFalse(j.isNull("message"));
assertEquals("null", j.getString("message"));
j = new JSONObject("{\"message\":null}");
assertTrue(j.isNull("message"));
assertEquals(null, j.getString("message")); // fail here: getString should return null instead of "null"
}
this is more a discussion, than an issue.
did you ever think about implementing the equals() and hashCode() functions in JSONObject, JSONArray and JSONString so that they recursively detect identical objects?
JSONObject a = new JSONObject();
a.put("key", "value");
JSONObject b = new JSONObject();
b.put("key", "value");
a.equals(b); //would return true
for example with this, JSON data object could be used in java-collections to be checked in their contains() function.
Hey Douglas,
I'm not sure if this is a bug, or intended behavior, but when you attempt to create a new JSONObject from a null string (for instance, new JSONObject(null)), you get back a NullPointerException, instead of what I would consider the expected, a JSONException.
Could you tell me your thoughts on this, and/or update the code accordingly?
Thanks,
Graham
All the maintained versions need to support it.
I'd probably be preferable to have the parser return a BigInteger instead of the current runtime exception. ;-)
java.lang.NumberFormatException: For input string: "213991133777039355058536718668104339937"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
at java.lang.Long.parseLong(Long.java:422)
at java.lang.Long.valueOf(Long.java:525)
at org.json.simple.parser.Yylex.yylex(Unknown Source)
at org.json.simple.parser.JSONParser.nextToken(Unknown Source)
at org.json.simple.parser.JSONParser.parse(Unknown Source)
at org.json.simple.parser.JSONParser.parse(Unknown Source)
at org.json.simple.parser.JSONParser.parse(Unknown Source)
at org.tgen.cortexio.store.LazyLocalDiskDocumentStore.loadJSONFromDisk(LazyLocalDiskDocumentStore.java:115)
at org.tgen.cortexio.store.LazyLocalDiskDocumentStore.loadDocumentFromDisk(LazyLocalDiskDocumentStore.java:135)
at org.tgen.cortexio.store.LazyLocalDiskDocumentStore.collectDocuments(LazyLocalDiskDocumentStore.java:259)
at org.tgen.cortexio.store.LazyLocalDiskDocumentStore.collectDocuments(LazyLocalDiskDocumentStore.java:252)
at org.tgen.cortexio.store.LazyLocalDiskDocumentStore.collectDocuments(LazyLocalDiskDocumentStore.java:252)
at org.tgen.cortexio.store.LazyLocalDiskDocumentStore.collectDocuments(LazyLocalDiskDocumentStore.java:252)
at org.tgen.cortexio.store.LazyLocalDiskDocumentStore.collectDocuments(LazyLocalDiskDocumentStore.java:252)
at org.tgen.cortexio.store.LazyLocalDiskDocumentStore.collectDocuments(LazyLocalDiskDocumentStore.java:252)
at org.tgen.cortexio.store.LazyLocalDiskDocumentStore.collectDocuments(LazyLocalDiskDocumentStore.java:252)
at org.tgen.cortexio.store.LazyLocalDiskDocumentStore.collectDocuments(LazyLocalDiskDocumentStore.java:252)
at org.tgen.cortexio.store.LazyLocalDiskDocumentStore.collectDocuments(LazyLocalDiskDocumentStore.java:252)
at org.tgen.cortexio.store.LazyLocalDiskDocumentStore.collectDocuments(LazyLocalDiskDocumentStore.java:252)
at org.tgen.cortexio.store.LazyLocalDiskDocumentStore.collectDocuments(LazyLocalDiskDocumentStore.java:252)
at org.tgen.cortexio.store.LazyLocalDiskDocumentStore.collectDocuments(LazyLocalDiskDocumentStore.java:252)
at org.tgen.cortexio.store.LazyLocalDiskDocumentStore.collectDocuments(LazyLocalDiskDocumentStore.java:252)
at org.tgen.cortexio.store.LazyLocalDiskDocumentStore.collectDocuments(LazyLocalDiskDocumentStore.java:252)
at org.tgen.cortexio.store.LazyLocalDiskDocumentStore.collectDocuments(LazyLocalDiskDocumentStore.java:252)
at org.tgen.cortexio.store.LazyLocalDiskDocumentStore.collectDocuments(LazyLocalDiskDocumentStore.java:252)
at org.tgen.cortexio.store.LazyLocalDiskDocumentStore.collectDocuments(LazyLocalDiskDocumentStore.java:252)
at org.tgen.cortexio.store.LazyLocalDiskDocumentStore.all(LazyLocalDiskDocumentStore.java:242)
at org.tgen.cortexio.store.LazyLocalDiskDocumentStoreTest.testCount(LazyLocalDiskDocumentStoreTest.java:44)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:28)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:31)
at org.junit.runners.BlockJUnit4ClassRunner.runNotIgnored(BlockJUnit4ClassRunner.java:79)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:71)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:49)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184)
at org.junit.runners.ParentRunner.run(ParentRunner.java:236)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
Hello,
Here in brazil we have phone numbers that start with 0800 and they get treated as ints thereby losing the first 0.
Tracked down the error to this bit of code in XML.java
try {
char initial = string.charAt(0);
boolean negative = false;
if (initial == '-') {
initial = string.charAt(1);
negative = true;
}
if (initial == '0' && string.charAt(negative ? 2 : 1) == '0') {
return string;
}
if ((initial >= '0' && initial <= '9')) {
if (string.indexOf('.') >= 0) {
return Double.valueOf(string);
} else if (string.indexOf('e') < 0 && string.indexOf('E') < 0) {
Long myLong = new Long(string);
if (myLong.longValue() == myLong.intValue()) {
return new Integer(myLong.intValue());
} else {
return myLong;
}
}
}
} catch (Exception ignore) {
}
It seems to want to convert any value 0XNNNN... (where X isn't 0 and N is any digit) as an int.
Any particular reason for this?
Hi,
Is there a way the latest version of the code could be pushed to the Maven Central repo because the latest version there (http://mvnrepository.com/artifact/org.json/json) is from 11.02.2009. and there have been some changes since then? Specifically, I need the remove() method in JSONArray class which wasn't implemented then.
I know I could package this code by myself and use it in my project, but I prefer having maven manage my dependencies. And also, this could just benefit other users and the project itself.
Thanks,
Nikola
Following test-code will not produce expected results, the array-elements of type BigDecimal will be incorrectly quoted. I guess other Number types like BigInteger will fail too.
Number[] foo = new Number[5];
foo[0] = BigDecimal.ZERO;
foo[1] = new Integer( 1 );
foo[2] = new BigDecimal( 1.2 );
foo[3] = new Integer( 3 );
foo[4] = new BigDecimal( 4 );
JSONStringer s = new JSONStringer();
s.object();
s.key( "bar" );
s.value( foo );
s.endObject();
System.out.println( s.toString() );
I located the problem in the JSONObject.wrap(Object object) method line 1547 (ff) where the half dozen "instanceof " comparision should be replaced by a single "intanceof Number".
(The original code where i stumbled into this bug produces "highcharts" from various oracle database queries and of course, highcharts fails to produce charts from strings. Using Doubles is also no option ...)
When rendering JSONString there is a difference how it's value is handled in these two methods:
IMHO in the second case a JSONException should be thrown to indicate the error because there is no way for the programmer to detect that invalid value.
Hello JSON team,
I notice a little Bug in the JSONArray class (java), method optString(int, String). When the value of the element is null, it actually contains a instance of the object JSONObject.Null. The test:
object != null
return true since the instance of the object Null is not the null value. The instance of Null is then convert into a String with "object.toString()", which return the String "null". From this point, it's impossible to know if the JSON object contains the value null, or the String "null". The code here should be similar to JSONObject.optString:
JSONArray.java line 558;
change the following line:
return object != null ? object.toString() : defaultValue;
to this line:
return object == null || JSONObject.NULL.equals(object) ? defaultValue : object.toString();
Thanks
Gael
Douglas, hello:
https://github.com/barchart/barchart-wrap-json
http://search.maven.org/#search|ga|1|barchart-wrap-json
our wrapper addresses these issues;
in case you are open to the idea, I can fork, change and pull
your project so json.org maven central artifacts are normalized
and released by you instead;
please note, that to promote your releases to maven central
you would would need to follow these instructions:
https://docs.sonatype.org/display/Repository/Sonatype+OSS+Maven+Repository+Usage+Guide
please let me know if you want to me to do this / and will you do this?
thank you;
Andrei.
I had created an enum, PrivacyState, that had a function named getPrivacyStates() that returned all of the PrivacyState enums. I then passed that array to JSONArray(Object obj) constructor. This causes a stack overflow.
I have since removed the function entirely in favor of values() that is built into enum, which solves my problem, but technically a similar situation could still cause the bug to appear.
Thanks.
Im trying to parse a simple JSON array, like this:
{ "test" : [1,2,3,4] }
and the JSONObject constructor throws the following exception:
Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - Erroneous ctor sym type:
at br.com.mercur.permgen.json.JSONTokener.nextValue(JSONTokener.java:366)
at br.com.mercur.permgen.json.JSONObject.(JSONObject.java:207)
at br.com.mercur.permgen.json.JSONObject.(JSONObject.java:309)
I've tryed to generate the JSON from the classes, and the exception persists. The code that i used to test:
ArrayList<String> list = new ArrayList<String>();
list.add("1");
list.add("2");
list.add("3");
JSONObject o = new JSONObject();
o.append("test", new JSONArray(list));
System.out.println(o.toString());
JSONObject o1 = new JSONObject(o.toString());
Sorry if i'm doing something wrong, but i really liked the classes, they suit my need of simplest way of accessing some data on JSON.
Thanks in advance, Jorge.
The equals
method of JSONObject#Null
violates the “non-nullity” requirement of the equals method in Java. Since null
in Java is not an Object, and does not provide an equals method, null.equals( JSONObject.NULL )
cannot return true
while JSONObject.NULL.equals( null )
does so. Hence, this equals implementation is not symetric and violates the contract of an equivalence relation. No object must be equal to null
.
Tools like the equals verifier fault this implementation because of this violation. Also the Java Development Tools in Eclipse complain because this class implements equals without implementing hashCode.
Since there is only one single instance of JSONObject#NULL
, I'd suggest to remove the equals method from JSONObject#Null
. Object#equals
is a perfect fit for this class.
Hello,
I try to use JSONObject like it :
JSONObject tmp = new JSONObject ();
tmp.put("name","feecochette");
tmp.put("data",tmp);
It makes a infinitive loop, that's anormal ?
Hi,
I'm having trouble understanding this code:
case '/':
if (b == '<') {
sb.append('');
}
sb.append(c);
break;
Why is escape character '' only appended when the previous character is <. Looking at JSON control characters, the '/' is always a control character and should be prefixed with . Yet the code doesn't do that.
Thanks,
A NPE can occur if we try to serialize a JSONArray that contains a 'null' value. The NPE occurs in JSONObject @ line 1509, which is:
} else if (value.getClass().isArray()) {
At this point 'value' can be null.
This can be fixed very easy. We just need to move the if statement @ line 1523 to be the first:
} else if (value == null || value.equals(null)) {
writer.write("null");
}
Both valueToString
and writeValue
have method calls of the form value.equals(null)
. If value is equal to null
then a call to null.equals(null)
is going to fail with a NullPointerException
.
Hi Douglas,
Just wanted to point out a bug in your otherwise wonderful code.
Currently, putting float values into a JSONObject is using the put(String, double) method.
Unfortunately, this type of cast causes floating point precision problems.
For example, the float number 6.99 is translated to the double 6.989999771118164
To solve this issue I added the following method to the JSONObject:
/**
* Put a key/double pair in the JSONObject.
*
* @param key A key string.
* @param value A float which is the value.
* @return this.
* @throws JSONException If the key is null or if the number is invalid.
*/
public JSONObject put(String key, float value) throws JSONException {
this.put(key, Double.parseDouble(String.valueOf(value)));
return this;
}
Hopefully you could add this bug fix to your code.
Guy
Currently there are 3 "unofficial" versions at http://mvnrepository.com/artifact/org.json/json.
All the "official" versions, and only them, need to be available there.
Would be nice not to have to jar these up when downloaded. Thanks!
Hi,
If I have an object as this:
{
value: 0xFFFFFFFF
}
then 'value' reads as 0 even when read using getLong(..). The reason for this is the stringToValue function where hexadecimal values are always parsed using Integer.parseInt. I have fixed this locally, but please also fix it here :)
-Øivind
At line 172 of Test.java file there's an "assertEquals" failing.
This is the expected:
{"cook_time":"3 hours","name":"bread","tagName":"recipe","childNodes":[{"tagName":"title","childNodes":["Basic bread"]},{"amount":8,"unit":"dL","tagName":"ingredient","childNodes":["Flour"]},{"amount":10,"unit":"grams","tagName":"ingredient","childNodes":["Yeast"]},{"amount":4,"unit":"dL","tagName":"ingredient","state":"warm","childNodes":["Water"]},{"amount":1,"unit":"teaspoon","tagName":"ingredient","childNodes":["Salt"]},{"tagName":"instructions","childNodes":[{"tagName":"step","childNodes":["Mix all ingredients together."]},{"tagName":"step","childNodes":["Knead thoroughly."]},{"tagName":"step","childNodes":["Cover with a cloth, and leave for one hour in warm room."]},{"tagName":"step","childNodes":["Knead again."]},{"tagName":"step","childNodes":["Place in a bread baking tin."]},{"tagName":"step","childNodes":["Cover with a cloth, and leave for one hour in warm room."]},{"tagName":"step","childNodes":["Bake in the oven at 180(degrees)C for 30 minutes."]}]}],"prep_time":"5 mins"}
and this is the actual one:
{"cook_time":"3 hours","childNodes":[{"childNodes":["Basic bread"],"tagName":"title"},{"unit":"dL","childNodes":["Flour"],"tagName":"ingredient","amount":8},{"unit":"grams","childNodes":["Yeast"],"tagName":"ingredient","amount":10},{"state":"warm","unit":"dL","childNodes":["Water"],"tagName":"ingredient","amount":4},{"unit":"teaspoon","childNodes":["Salt"],"tagName":"ingredient","amount":1},{"childNodes":[{"childNodes":["Mix all ingredients together."],"tagName":"step"},{"childNodes":["Knead thoroughly."],"tagName":"step"},{"childNodes":["Cover with a cloth, and leave for one hour in warm room."],"tagName":"step"},{"childNodes":["Knead again."],"tagName":"step"},{"childNodes":["Place in a bread baking tin."],"tagName":"step"},{"childNodes":["Cover with a cloth, and leave for one hour in warm room."],"tagName":"step"},{"childNodes":["Bake in the oven at 180(degrees)C for 30 minutes."],"tagName":"step"}],"tagName":"instructions"}],"tagName":"recipe","name":"bread","prep_time":"5 mins"}
" " != ""
May be remove this trim, because in terms of XML is wrong. There is no way to restore the information, encoded in the spaces!
public Object nextContent() throws JSONException {
char c;
StringBuffer sb;
c = next();
/*
* do { c = next(); } while
* (Character.isWhitespace(c));
*/
if (c == 0) {
return null;
}
if (c == '<') {
return XML.LT;
}
sb = new StringBuffer();
for (;;) {
if (c == '<' || c == 0) {
back();
//return sb.toString().trim();
return sb.toString();
}
if (c == '&') {
sb.append(nextEntity(c));
} else {
sb.append(c);
}
c = next();
}
}
Also, in transformation JSONObject -> Xml.toString - > Xml.toJSONObject lost leading zeros.
It would be logical not to parse a string containing a number as numerical types, and provide the user to get them as numerical types.
Why is there the notion of nesting in the first place? It doesn't seem to comply with the JSON definition (there is no limit on nesting in the language, or is it?) . How was the exact value of JSONWriter.maxdepth determined? Why is it not exposed / overrideable via constructor?
See discussion in #123.
Proposed actions include:
In my opinion it would be useful to replace the HashMap
in JSONObject
with a LinkedHashMap
to maintain the order of the inserted values. This is would be really helpful if one wants to create JSON files that are easy to read and easy to compare with the original files. Also it is more helpful when iterating through the objects since the values come in the order you expect them.
Can you explain why you included the range of characters between \u2000 and \u2100 in the section of the quote() method that escapes characters? I understand why the other two ranges are escaped, and I understand that any character may be escaped, I'm just looking for the reasoning behind escaping that particular range of characters.
Thanks in advance.
If you have an attribute name of "content", XML.toString(json) will fail. Workaround is to change XML class to use an more unique identifier other than "content".
{"Profile": { "list": {"history": { "entries": [{"deviceId": "id","content": {"material": [{"stuff": false}]}}]}}}}
When using JSONML to convert XML into JSON, there seems to be an issue when encountering comments.
I think the issue is at line 95:
c = x.next();
if (c == '-') {
if (x.next() == '-') {
x.skipPast("-->");
}
x.back();
} else if (c == '[') {
Should there be an else before the x.back(), or maybe the x.back() shouldnt even be in there.
Take the following XML snippet as an example.
<?xml version="1.0" encoding="UTF-8"?>
<subsonic-response xmlns="http://subsonic.org/restapi" status="ok" version="1.6.0">
<playlists>
<playlist id="476c65652e6d3375" name="Mood"/>
<playlist id="50617274792e78737066" name="Party"/>
</playlists>
</subsonic-response>
the playlist
elements have id's that are hexadecimal strings.
in <playlist id="50617274792e78737066" name="Party"/>
the id can also be interpreted as an exponential number. This makes the conversion of this snippet fail with the message: org.json.JSONException: JSON does not allow non-finite numbers
I don't know if there is a way to tell the difference between a number and a string from XML but I think the problem could be avoided if instead of throwing an exception the implementation interprets the infinite number as a string in any case.
It doesn't look like you've published to maven central in quite a while. Are you planning to?
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.