Convert a Bundle to JSON

后端 未结 4 1763
攒了一身酷
攒了一身酷 2020-12-24 06:49

I\'d like to convert the an Intent\'s extras Bundle into a JSONObject so that I can pass it to/from JavaScript.

Is there a quick or best way to do this conversion? I

4条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-24 07:44

    You can use Bundle#keySet() to get a list of keys that a Bundle contains. You can then iterate through those keys and add each key-value pair into a JSONObject:

    JSONObject json = new JSONObject();
    Set keys = bundle.keySet();
    for (String key : keys) {
        try {
            // json.put(key, bundle.get(key)); see edit below
            json.put(key, JSONObject.wrap(bundle.get(key)));
        } catch(JSONException e) {
            //Handle exception here
        }
    }
    

    Note that JSONObject#put will require you to catch a JSONException.

    Edit:

    It was pointed out that the previous code didn't handle Collection and Map types very well. If you're using API 19 or higher, there's a JSONObject#wrap method that will help if that's important to you. From the docs:

    Wrap an object, if necessary. If the object is null, return the NULL object. If it is an array or collection, wrap it in a JSONArray. If it is a map, wrap it in a JSONObject. If it is a standard property (Double, String, et al) then it is already wrapped. Otherwise, if it comes from one of the java packages, turn it into a string. And if it doesn't, try to wrap it in a JSONObject. If the wrapping fails, then null is returned.

提交回复
热议问题