问题
I have an Android app which in some places generates JSON, serialises it, and then at a later time de-serialises it and uses the data. I'm using the builtin JSONObject On Android 5 and up which looks the org.json package.
My app runs fine on all Android 5.0 and newer devices, but on Android 4.x it fails in some places. Looking in the debugger the de-serialised JSONObject looks somewhat broken.
This seems like some kind of bug in the JSON library that ships with older android, and I'd like to simply use a newer up to date version from MavenCentral or JCenter
How do I do this? I've added
compile 'org.json:json:20160212'
To my app's build.gradle dependencies section, but it doesn't seem to make any difference.
Is this possible or does the old busted android system library always win?
Update: It turns out not to be a bug in JSON parsing, but in JSON generation. The app was generating JSON from Java Map
and List
objects - which in Android 4 results in incorrect string output:
More details here:
http://fupeg.blogspot.co.nz/2011/07/android-json-bug.html
I've worked around the problem by writing the following two functions:
public static JSONObject mapToJSON(Map<String,Object> map){
HashMap<String,Object> fixed = new HashMap<>();
for (String key : map.keySet()){
Object value = map.get(key);
if (value instanceof Map){
value = mapToJSON((Map<String,Object>) value);
} else if (value instanceof List) {
value = listToJSON((List<Object>)value);
}
fixed.put(key,value);
}
return new JSONObject(fixed);
}
public static JSONArray listToJSON(List<Object> list) {
JSONArray result = new JSONArray();
for (Object value : list){
if (value instanceof Map){
value = mapToJSON((Map<String,Object>) value);
} else if (value instanceof List) {
value = listToJSON((List<Object>)value);
}
result.put(value);
}
return result;
}
And replacing all calls in the app
new JSONObject(someList)
replaced withlistToJSON(someList)
new JSONObject(someMap)
replaced withmapToJSON(someMap)
The question still stands though. It'd be much better if I didn't have to implement this workaround, and could instead bundle a newer version of the org.json
library for use on Android 4.0. Does anyone know how I might do this on Android? Or if it's not possible?
来源:https://stackoverflow.com/questions/37317669/android-4-json-generation-bug-can-i-use-a-newer-version-of-the-org-json-library