title: Converting a Bundle that contains bundles to JSON
body: <p>I have a bundle that I would like to convert to one big JSONObject so that I can send it through a web service later on.  This main bundle contains mainly strings and integers, but it also contains another bundle, which in that contains bundles that have sets of 4 key value pairs.  </p>
  
  <p>Here is a diagram to clear up any confusion:
  <a href="https://i.stack.imgur.com/FIzJS.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/FIzJS.png" alt="enter image description here"></a></p>
  
  <p>Code:</p>
  
  <pre><code>private JSONObject convertBundleToJSON(Bundle b)
  {
      //the main json object to be returned
      JSONObject json = new JSONObject();
  
  
      Set&lt;String&gt; 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&lt;Bundle&gt; bundles = (Set&lt;Bundle&gt;) 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;
  }
  </code></pre>
  
  <p>But I get a casting exception at the error line.  It doesn't like the cast between bundle and set.  Any ideas or alternative ways to get around this?</p>