gpt4 book ai didi

java - 将 Bundle 转换为 JSON

转载 作者:IT老高 更新时间:2023-10-28 12:52:48 26 4
gpt4 key购买 nike

我想将 Intent 的 extras Bundle 转换为 JSONObject,以便可以将其传递给 JavaScript。

有没有一种快速或最佳的方法来进行这种转换?如果不是所有可能的 Bundles 都可以工作,那也没关系。

最佳答案

您可以使用 Bundle#keySet() 来获取 Bundle 包含的键列表。然后,您可以遍历这些键并将每个键值对添加到 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
}
}

请注意,JSONObject#put 将要求您捕获 JSONException

编辑:

有人指出,前面的代码没有很好地处理CollectionMap类型。如果您使用 API 19 或更高版本,则有一个 JSONObject#wrap 方法可以帮助您,如果这对您很重要。来自 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.

关于java - 将 Bundle 转换为 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21858528/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com