【问题标题】:Converting a Bundle that contains bundles to JSON将包含捆绑包的捆绑包转换为 JSON
【发布时间】: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 之间的转换。有什么想法或替代方法可以解决这个问题?

【问题讨论】:

    标签: java android json bundle


    【解决方案1】:

    您可以通过创建一个可打包的模型类来简单地实现这一点,而不是采用这种复杂的方式。

    只需将这些 json 添加到该模型并进一步传递它,使用它会更简单。

    【讨论】:

      猜你喜欢
      • 2016-01-26
      • 1970-01-01
      • 1970-01-01
      • 2012-06-29
      • 2014-11-03
      • 2014-11-21
      • 2023-03-07
      • 2015-01-25
      • 1970-01-01
      相关资源
      最近更新 更多