2016-04-05 52 views
0

我試圖用下面的代碼創建一個json數組。在json數組中嵌套多個jsonobjects

private JSONArray getJsonArray(String encodedString) { 
    JSONArray docArray = new JSONArray(); 
    JSONObject docprops = new JSONObject(); 
    JSONObject innerJson = new JSONObject(); 
    JSONArray innerJsonArray = new JSONArray(); 
    JSONObject inJobj = new JSONObject(); 
    JSONArray outerJsonArray = new JSONArray(); 
    SharedPreferences userDetails = getSharedPreferences("userdetails", Context.MODE_PRIVATE); 
    String session = userDetails.getString("session", ""); 

    try { 
     innerJson.put("compliance_history_id", compliance_history_id); 

     docprops.put("file_size", fileSize); 
     docprops.put("file_name", fileName); 
     docprops.put("file_content", encodedString); 

     docArray.put(docprops); 

     innerJson.put("documents", docArray); 
     innerJson.put("completion_date", mCompletedDate.getText().toString()); 
     innerJson.put("validity_date", JSONObject.NULL); 
     innerJson.put("next_due_date", mNextDueDate.getText().toString()); 
     innerJson.put("remarks", mRemarks.getText().toString()); 

     innerJsonArray.put("UpdateComplianceDetail"); 
     innerJsonArray.put(innerJson); 

     inJobj.put("session_token", session); 
     inJobj.put("request", innerJsonArray); 

     outerJsonArray.put(session); 
     outerJsonArray.put(inJobj); 

    } catch (JSONException e) { 
     e.printStackTrace(); 
    } 

    return outerJsonArray; 
} 

這是我的代碼是框架的JSON ..

[ 
    "1-e4077f4a346440ecaeaf5f3387d47775", 
    { 
    "request": [ 
     "UpdateComplianceDetail", 
     { 
     "remarks": "Remarks", 
     "next_due_date": "27-Mar-2016", 
     "completion_date": "31-may-2017", 
     "validity_date": null, 
     "documents": [ 
      { 
      "file_name": "20160404_135811.jpg", 
      "file_size": 24, 
      "file_content": "iVBORw0KGgoAAAANSUhEUgAAABIAAAASCAQAAAD8x0bcAAAABGdBTUEAALGPC/xhBQAAACBjSFJNAAB6JgAAgIQAAPoAAACA6AAAdTAAAOpgAAA6mA" 
      } 
     ], 
     "compliance_history_id": 49 
     } 
    ], 
    "session_token": "1-e4077f4a346440ecaeaf5f3387d47775" 
    } 
] 
  1. 有可能是正在上傳所以document陣列可能包含在其內的多個JSON對象多個文檔。我怎麼能做到這一點?
  2. 是否有任何方法可以優化上述代碼,而不是通過使用gson或jackson?

回答

1

如果documents是一個數組,迭代通過JSONArray對象

JSONArray jsonObjectArray= updateComplianceDetailresponse.getJSONArray("documents"); 
LinkedList arrayCompliance=new LinkedList(); 
for(int count=0;count<jsonObjectArray.length();count++){ 
    // iterate and get required elements 
    //Add to arrayCompliance LinkedList 

} 
1

如果可能具有內部docArray多個對象,則下面線路應內部的for循環。

JSONObject docprops = new JSONObject(); 
    docprops.put("file_size", fileSize); 
    docprops.put("file_name", fileName); 
    docprops.put("file_content", encodedString); 
    docArray.put(docprops); 

SO根據文檔對象數量可以throught的迭代for循環和每次迭代創建一個JSONObject並把它的docArray