2016-03-07 37 views
1

我有一個我想轉換爲一個大的JSONObject的包,以便稍後通過Web服務發送它。這個主包主要包含字符串和整數,但它也包含另一個包,其中包含具有4個鍵值對的包。將包含捆綁包的包轉換爲JSON

這裏有一個圖來消除混淆: enter image description here

代碼:

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; 
} 

,但我得到的錯誤行鑄造例外。它不喜歡捆綁和集合之間的轉換。任何想法或替代方法來解決這個問題?

回答

0

而不是做這種複雜的方式,你可以簡單地通過創建一個可分類的模型類來實現這一點。

只需將這些json添加到該模型並進一步傳遞它,使用它會更簡單。

相關問題