Skip to content
Advertisement

Convert a Bundle to JSON

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? It would be alright if not all possible Bundles will work.

Advertisement

Answer

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<String> 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.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement