I'm using a shared library in both Android and Java and have found this inconsistency on its behavior.
The library depends on org.json.JSONObject. Which is in a jar contained on the library itself, but it seems that somehow Android overrides that jar with its own implementation of JSON.
When I do:
Double a = 0.1;
JSONObject b = new JSONObject();
b.put("Hola", a);
flockSONversionString = b.getString("Hola");
In Android, it runs with no problems, but in Java, it throws an exception because 0.1 is not a String. The second behavior is the one that I expected from the beginning.
when I do
Object aObj = b.get("Hola");
if(aObj instanceof Float){
System.out.println("Hola is Float");
} else if (aObj instanceof Long){
System.out.println("Hola is Long");
} else if (aObj instanceof Double){
System.out.println("Hola is Double");
} else if (aObj instanceof String){
System.out.println("Hola is String");
} else {
System.out.println("Hola has unknown type");
}
Both in Android and Java I get Hola is Double.
The curious thing is that, if you go to the source code of org.json.JSONObject the getString() method is declared as follows:
public String getString(String key) throws JSONException {
Object object = get(key);
if (object instanceof String) {
return (String)object;
}
throw new JSONException("JSONObject[" + quote(key) +
"] not a string.");
}
Which seems totally as the expected behavior because it's checking if the Object is a String and throwing an exception if it isn't.
Any idea why would this be happening?
Thank you!
(I can't change the dependency on org.json.JSONObject since this would break the compatibility between Android and Java )
Are you sure you are using the same jar in both projects?
Android's org.json.JSONObject.toString(String) is different:
/**
* Returns the value mapped by {@code name} if it exists, coercing it if
* necessary, or throws if no such mapping exists.
*
* @throws JSONException if no such mapping exists.
*/
public String getString(String name) throws JSONException {
Object object = get(name);
String result = JSON.toString(object);
if (result == null) {
throw JSON.typeMismatch(name, object, "String");
}
return result;
}
JSON.toString(Object):
static String toString(Object value) {
if (value instanceof String) {
return (String) value;
} else if (value != null) {
return String.valueOf(value);
}
return null;
}
In your case this would not throw an exception on Android.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With