转换一个包以JSON [英] Convert a Bundle to JSON

查看:192
本文介绍了转换一个包以JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想转换一个Intent的额外捆绑成一个JSONObject的,这样我可以把它传递到/从JavaScript。

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.

推荐答案

您可以使用捆绑#键设置()来获得一个包包含键列表。然后,您可以遍历这些密钥,并添加每个键 - 值对成的JSONObject

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
    }
}

注意的JSONObject#把将要求您搭上 JSONException

编辑:

据指出,previous code没有处理集合地图类型非常好。如果您使用的是API 19或更高,有一个的JSONObject#包装的方法,这将有助于如果这对你很重要。从文档

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:

包裹一个目的,如果需要的话。如果对象为空,则返回空   目的。如果它是一个数组或集合,包装在一个JSONArray。如果它   是一张地图,把它包在一个JSONObject的。如果它是一个标准的属性   (双人间,字符串等),那么它已经裹。否则,如果它   来自的Java包之一,把它变成一个字符串。如果它   不,尝试把它包在一个JSONObject的。如果包装失败,那么   返回null。

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.

这篇关于转换一个包以JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆