首页 > 解决方案 > 安卓 API 15-18 | JSONObject 兼容性问题

问题描述

问题

在 Android 版本 15 到 18 中,使用org.json.JSONObject该类解析 JSON-String 的工作方式与在较新版本上不同。

// EDIT: this wasn't a String; It was a subclass of HashMap
String someWorkingJsonString = "{\"\":{array:[{text..."; 
System.out.println( new JSONObject( someWorkingJsonString ) );
// output on Android 3.2 (API 16) [messed up double quotes]
I/System.out: {"":"{array:[{text:...
// output on Android 5.1 (API 22) [working]
I/System.out: {"":{"array":[{"text":...

问题的原因

仔细查看org.json.JSONObject 源代码会发现,在版本 19 中,warp()line 138.

// source code on Android API 15 - 18 [messed up double quotes]
/* 138 */  nameValuePairs.put(key, entry.getValue());
// source code on Android API 19 and up [working]
/* 138 */  nameValuePairs.put(key, wrap(entry.getValue()));
// implementation of the warp method on Android API 19 and up
/**
* Wraps the given object if necessary.
*
* <p>If the object is null or , returns {@link #NULL}.
* If the object is a {@code JSONArray} or {@code JSONObject}, no wrapping is necessary.
* If the object is {@code NULL}, no wrapping is necessary.
* If the object is an array or {@code Collection}, returns an equivalent {@code JSONArray}.
* If the object is a {@code Map}, returns an equivalent {@code JSONObject}.
* If the object is a primitive wrapper type or {@code String}, returns the 
* Otherwise if the object is from a {@code java} package, returns the result of {@code toString}.
* If wrapping fails, returns null.
*/
public static Object wrap(Object o) {
    if (o == null) {
        return NULL;
    }
    if (o instanceof JSONArray || o instanceof JSONObject) {
        return o;
    }
    if (o.equals(NULL)) {
        return o;
    }
    try {
        if (o instanceof Collection) {
            return new JSONArray((Collection) o);
        } else if (o.getClass().isArray()) {
            return new JSONArray(o);
        }
        if (o instanceof Map) {
            return new JSONObject((Map) o);
        }
        if (o instanceof Boolean ||
            o instanceof Byte ||
            o instanceof Character ||
            o instanceof Double ||
            o instanceof Float ||
            o instanceof Integer ||
            o instanceof Long ||
            o instanceof Short ||
            o instanceof String) {
            return o;
        }
        if (o.getClass().getPackage().getName().startsWith("java.")) {
            return o.toString();
        }
    } catch (Exception ignored) {
    }
    return null;
}

问题

如何解决旧版本 android 的描述问题?

提前致谢

标签: javaandroidjson

解决方案


推荐阅读