Java 将捆绑包转换为 JSON
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21858528/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert a Bundle to JSON
提问by Murph
I'd like to convert the an Intent's extras Bundle into a JSONObject so that I can pass it to/from JavaScript.
我想将 Intent 的 extras Bundle 转换为 JSONObject,以便我可以将它传递给/从 JavaScript 传递。
Is there a quick or best way to do this conversion? It would be alright if not all possible Bundles will work.
有没有快速或最好的方法来进行这种转换?如果不是所有可能的捆绑包都可以工作,那也没关系。
采纳答案by Makario
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
:
您可以使用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
}
}
Note that JSONObject#put
will require you to catch a JSONException
.
请注意,这JSONObject#put
将要求您捕获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:
有人指出,之前的代码没有很好地处理Collection
和Map
键入。如果您使用 API 19 或更高版本,那么JSONObject#wrap
如果这对您很重要,那么有一种方法会有所帮助。从文档:
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.
如有必要,包裹一个对象。如果对象为空,则返回空对象。如果是数组或集合,则将其包装在 JSONArray 中。如果是地图,则将其包装在 JSONObject 中。如果它是标准属性(Double、String 等),那么它已经被包装了。否则,如果它来自 java 包之一,则将其转换为字符串。如果没有,请尝试将其包装在 JSONObject 中。如果包装失败,则返回 null。
回答by Carlos Andres Acevedo
Object myJsonObj = bundleObject.get("yourKey");
JsonParser parser = new JsonParser();
JsonObject json = parser.parse(myJsonObj.toString()).getAsJsonObject();
json.get("memberInJson").getAsString();
回答by Dmitry
private String getJson(final Bundle bundle) {
if (bundle == null) return null;
JSONObject jsonObject = new JSONObject();
for (String key : bundle.keySet()) {
Object obj = bundle.get(key);
try {
jsonObject.put(key, wrap(bundle.get(key)));
} catch (JSONException e) {
e.printStackTrace();
}
}
return jsonObject.toString();
}
public static Object wrap(Object o) {
if (o == null) {
return JSONObject.NULL;
}
if (o instanceof JSONArray || o instanceof JSONObject) {
return o;
}
if (o.equals(JSONObject.NULL)) {
return o;
}
try {
if (o instanceof Collection) {
return new JSONArray((Collection) o);
} else if (o.getClass().isArray()) {
return toJSONArray(o);
}
if (o instanceof Map) {
return new JSONObject((Map) o);
}
if (o instanceof Boolean ||
o instanceof Byte ||
o instanceof Character ||
o instanceof Double ||
o instanceof Float ||
o instanceof Integer ||
o instanceof Long ||
o instanceof Short ||
o instanceof String) {
return o;
}
if (o.getClass().getPackage().getName().startsWith("java.")) {
return o.toString();
}
} catch (Exception ignored) {
}
return null;
}
public static JSONArray toJSONArray(Object array) throws JSONException {
JSONArray result = new JSONArray();
if (!array.getClass().isArray()) {
throw new JSONException("Not a primitive array: " + array.getClass());
}
final int length = Array.getLength(array);
for (int i = 0; i < length; ++i) {
result.put(wrap(Array.get(array, i)));
}
return result;
}
回答by inder
Here is a Gson type adapter factory that converts a Bundle to JSON.
这是一个将 Bundle 转换为 JSON 的 Gson 类型适配器工厂。