Android 4 JSON generation bug: Can I use a newer version of the org.JSON library than the bundled one?

拟墨画扇 提交于 2020-01-03 03:09:31

问题


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 with listToJSON(someList)
  • new JSONObject(someMap) replaced with mapToJSON(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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!