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.
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.
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 aJSONObject
:Note that
JSONObject#put
will require you to catch aJSONException
.Edit:
It was pointed out that the previous code didn't handle
Collection
andMap
types very well. If you're using API 19 or higher, there's aJSONObject#wrap
method that will help if that's important to you. From the docs:Here is a Gson type adapter factory that converts a Bundle to JSON.
https://github.com/google-gson/typeadapters/blob/master/android/src/main/java/BundleTypeAdapterFactory.java