我想將Intent的額外套件轉換爲JSONObject,以便我可以將它傳遞給JavaScript。將套件轉換爲JSON
是否有快速或最好的方式來做這種轉換?如果不是所有可能的Bundle都能正常工作,那就沒問題了。
我想將Intent的額外套件轉換爲JSONObject,以便我可以將它傳遞給JavaScript。將套件轉換爲JSON
是否有快速或最好的方式來做這種轉換?如果不是所有可能的Bundle都能正常工作,那就沒問題了。
您可以使用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
。
編輯:
有人指出,以前的代碼沒有處理Collection
和Map
類型非常好。如果您使用API 19或更高版本,那麼有一個JSONObject#wrap
方法,如果這對您很重要,將會有所幫助。從docs:
如有必要,請包裹一個對象。如果該對象爲空,則返回NULL 對象。如果它是一個數組或集合,則將其包裝在JSONArray中。如果它是 是一個映射,則將其包裝在一個JSONObject中。如果它是標準屬性 (Double,String等),則它已被包裝。否則,如果 來自其中一個Java包,請將其轉換爲字符串。如果它不是 ,請嘗試將其包裝在JSONObject中。如果包裝失敗,則返回 null。
此實現似乎無法正確處理地圖或列表。你應該檢查你從bundle中得到的對象的類型,如果它是一個可以使用新的JSONObject(map)構造函數的地圖,並且它是一個列表,你可以使用新的JSONArray(列表) –
好的調用。如果您不想執行檢查,那麼還有一個'JSONObject#wrap'方法可以爲您打包。 – Makario
很酷。我不知道這個功能是否存在,這使得它更容易。 –
Object myJsonObj = bundleObject.get("yourKey");
JsonParser parser = new JsonParser();
JsonObject json = parser.parse(myJsonObj.toString()).getAsJsonObject();
json.get("memberInJson").getAsString();
我使用了gson,因爲JSONObject.wrap需要Build 19.如果你有一個使用gson反序列化的期望對象。 :P –
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;
}
這裏是一個GSON型適配器工廠,一個包轉換成JSON。
你有什麼額外的東西? – Melquiades
我不想處理特定的演員組合。我想要一些通用代碼來完成它,因爲這個代碼路徑可以被其他開發者使用,而不是我自己的任意數據。 – Murph