【发布时间】:2016-03-07 21:07:42
【问题描述】:
我有一个捆绑包,我想将其转换为一个大的 JSONObject,以便稍后通过 Web 服务发送它。这个主包主要包含字符串和整数,但它还包含另一个包,其中包含具有 4 个键值对集的包。
代码:
private JSONObject convertBundleToJSON(Bundle b)
{
//the main json object to be returned
JSONObject json = new JSONObject();
Set<String> keys = b.keySet();
for (String key : keys) {
try {
// json.put(key, bundle.get(key)); see edit below
json.put(key, JSONObject.wrap(b.get(key)));
} catch(JSONException e) {
//Handle exception here
Log.d("Convert Bund", e.toString());
}
}
JSONObject fvl = new JSONObject();
int i = 0;
//error right here - b is a bundle of bundles; trying to iterate through
Set<Bundle> bundles = (Set<Bundle>) b.get("field_value_list");
for (Bundle bun : bundles)
{
JSONObject f = new JSONObject();
try {
f.put("fld_value_decode", bun.get("fld_value_decode"));
f.put("fld_id", bun.get("fld_id"));
f.put("fld_value", bun.get("fld_value"));
f.put("fld_name", bun.get("fld_name"));
fvl.put(i+"",f);
i++;
} catch(JSONException e) {
//Handle exception here
Log.d("FVL Convert Bund", e.toString());
}
}
try {
json.put("field_value_list", fvl);
} catch (JSONException e) {
e.printStackTrace();
}
return json;
}
但是我在错误行得到一个强制转换异常。它不喜欢 bundle 和 set 之间的转换。有什么想法或替代方法可以解决这个问题?
【问题讨论】: