2017-01-04 84 views
0

我有這樣的JSONObject的價值觀到另一個JSONObject的與鍵值對

{ 

     "result": 
{ 

    "issue_date": "xx-yy-zzzz", 
    "father/husband": "TEST", 
    "name": "ABC ", 
    "blood_group": "", 
    "dob": "xx-yy-zzzz", 
    "validity": { 
     "non-transport": "xx-yy-zzzz to xx-yy-zzzz", 
     "transport": "xx-yy-zzzz to xx-yy-zzzz" 
    }, 
    "cov_details": { 
     "MCWG": "NA", 
     "3WTR": "NA", 
     "PSV BUS": "NA", 
     "LMV": "NA", 
     "INVCRG": "NA" 
    }, 
    "address": "ABC" 
    } 
} 

 JSONObject dlData = new JSONObject(); 
    JSONObject dlObj = new JSONObject(); 
    JSONObject dlcov = new JSONObject(); 
    JSONObject dlCovs = new JSONObject(); 
    dlCov = jsonObject.getJSONObject("result").getJSONObject("cov_details"); 

一個JSON訪問cov_details的數據, 我使用這個代碼塊存儲細節呈現內cov_details對象

  dlcov = jsonObject.getJSONObject("result").getJSONObject("cov_details"); 
     Iterator<String> x = dlcov.keys(); 
      while (x.hasNext()){ 
       String key1 = x.next(); 
       String value1 = dlcov.optString(key1); 
       dlCovs.put("covabbrv",key1); 
       dlCovs.put("dcIssuedt",value1); 
       dlCovs.put("vecatg",key1); 

      } 

     dlData.put("dlCovs", dlCovs); 

我試圖保存在d每值lCovs,但它只存儲對象中的最後一個值,無論如何,我們可以使用它存儲dlCovs objet中的所有值,並將其值存儲爲Key值並迭代它。任何幫助都將非常可觀,非常感謝。 進入這裏

+0

凡'dlCovs'定義? – shmosel

+0

shmosel它是在範圍內定義的另一個JSONObject,我忘了提及, JSONObject dlCovs = new JSONObject(); – Mavericks

+0

請[編輯](http://stackoverflow.com/posts/41455050/edit)您的文章與任何額外的代碼。 – shmosel

回答

1

使用JSONArray爲covabbrv,dcIssuedt和vecatg

JSONArray covabbrv = new JSONArray(); 
JSONArray dcIssuedt = new JSONArray(); 
JSONArray vecatg = new JSONArray(); 
Iterator<String> x = dlcov.keys(); 
    while (x.hasNext()){ 
     String key1 = x.next(); 
     String value1 = dlcov.optString(key1); 
     covabbrv.put(key1); 
     dcIssuedt.put(value1); 
     vecatg.put(key1); 
    } 
dlCovs.put("covabbrv",covabbrv); 
dlCovs.put("dcIssuedt",dcIssuedt); 
dlCovs.put("vecatg",vecatg); 

輸出將不會停,如:

{ 
    "covabbrv" : ["MCWG", "3WTR", "PSV BUS", "LMV", "INVCRG"], 
    "dcIssuedt" : ["NA", "NA", "NA", "NA", "NA"], 
    "vecatg" : ["MCWG", "3WTR", "PSV BUS", "LMV", "INVCRG"] 
} 
+0

比你這麼多OBit它爲我工作 – Mavericks

0

隨着dlCovs作爲JSONArray代碼,我會做這樣的事情:

JSONArray dlCovs = new JSONArray(); 
dlcov = jsonObject.getJSONObject("result").getJSONObject("cov_details"); 
Iterator<String> x = dlcov.keys(); 
while (x.hasNext()) { 
    String key1 = x.next(); 
    String value1 = dlcov.optString(key1); 

    JSONObject currentDlCov = new JSONObject(); 
    currentDlCov.put("covabbrv",key1); 
    currentDlCov.put("dcIssuedt",value1); 
    currentDlCov.put("vecatg",key1); 

    dlCovs.add(currentDlCov); 
} 

dlData.put("dlCovs", dlCovs); 

這將添加一個JSONObjects的數組,就好像你dlData的JSONObject一個的dlCovs值。