在 Android 中从更大的捆绑包中获取内部捆绑包

Getting an inner bundle from a bigger bundle in Android

我的 Android 代码中有一个函数,我在其中获取一个包作为输入:

void f(Bundle data)

这个data其实就是一个json的形式。假设它是以下格式: {"a":"x", "b":"y", "content":{"a1":"x1", "b1":"y1"}}

在这种情况下,如果我想获取 a 或 b 的值,那么我需要执行 String a = data.getString("a"); 来获取字符串 "x"。同样,String content = data.getString("content") 会 return 我的字符串 {"a1":"x1", "b1":"y1"}}。但我无法弄清楚如何在内容本身中获取特定值。有没有什么办法可以让 contentdata 一样作为另一个包,这样我就可以通过 content.getString("a1") 或类似的方式获取其中的值。这可能吗?

JSONObject jOBj = new JSONobject(data.getString("content"));
String a1 = jOBj.getString("x1");
String b1 = jOBj.getString("y1");

试试这个

从 bundle 获取值并创建 JSon 对象/Hashmap

private void createFlatJSon(Bundle appRestrictions,JSONObject jsonObject) throws JSONException{
    for (String key : appRestrictions.keySet()) {
        if (appRestrictions.get(key) instanceof Bundle) {
            createFlatJSon((Bundle) appRestrictions.get(key),jsonObject);
        }else if (appRestrictions.get(key) instanceof Parcelable[]){
            for (int i=0;i< ((Parcelable[]) appRestrictions.get(key)).length; i++){
                createFlatJSon((Bundle)((Parcelable[]) appRestrictions.get(key))[i],jsonObject);
            }
            //Log.e("KEY skipped",appRestrictions.get(key).toString());
        }else{

           Log.e("KEY: ",key+" Value:"+appRestrictions.get(key).toString());
            jsonObject.put(key,appRestrictions.get(key).toString());

        }
    }


}