2015-06-10 113 views
0

我想創建一個JSON結構是這樣的:添加JSON對象在另一個JSON對象爲Android

{ 
"request": { 
"slice": [ 
    { 
    "origin": "BLR", 
    "destination": "CCU", 
    "date": "2015-06-18" 
    } 
], 
"passengers": { 
    "adultCount": 1, 
    "infantInLapCount": 0, 
    "infantInSeatCount": 0, 
    "childCount": 0, 
    "seniorCount": 0 
}, 
"solutions": 20, 
"refundable": false 
} 
} 

爲此,我寫了下面的代碼行:

JSONObject request_hdr = new JSONObject(); 
    JSONObject request = new JSONObject(); 
    JSONArray slice = new JSONArray(); 
    JSONObject data = new JSONObject(); 

    data.put("origin",Origin); 
    data.put("destination",Destination); 
    data.put("date", Start_Date); 
    slice.put(data); 
    request.put("slice",slice); 
    request_hdr.put("request",request); 

    JSONObject addl_info = new JSONObject(); 
    addl_info.put("adultCount",Num_Adult); 
    addl_info.put("infantInLapCount",Num_Infant); 
    addl_info.put("infantInSeatCount", 0); 
    addl_info.put("childCount",0); 
    addl_info.put("seniorCount",0); 
    request.put("passengers",addl_info); 
    request_hdr.put("request",request); 

    JSONObject solutions = new JSONObject(); 
    solutions.put("solutions", 20); 

    JSONObject refundable = new JSONObject(); 
    refundable.put("refundable","false"); 

我無法將JSON對象的「解決方案」和「可退還」添加到根對象的「請求」中。

任何人都可以幫助我嗎?另外我不確定(即從未測試過解析JSON),如果上面的代碼運行正常或不正確。

任何幫助/建議,將不勝感激。提前致謝!

+0

你在哪裏添加'解決方案'和'refundable'到'請求'在這個代碼?我什麼都看不到。 – Tukajo

+0

'requests.put(「solutions-key」,solutionsObject)' – Tukajo

+0

是的,我嘗試了一些..但它沒有工作......所以我把它留在你身上:) –

回答

0

如果這是你的代碼的末尾,

JSONObject solutions = new JSONObject(); 
solutions.put("solutions", 20); 

JSONObject refundable = new JSONObject(); 
refundable.put("refundable","false"); 

那麼問題是你從來沒有真正加入的對象到您request對象。

而且,那些價值觀,而不是JSONObjects,所以你應該將其替換爲:

requests.put("solutions", 20); 
requests.put("refundable", false); 

,如果你希望它的結構在原來的職位相匹配。

+0

Thanks @Guardanis!有效。 :) 我現在明白了。這個問題有點傻! :) –

+0

很高興我能幫忙! – Guardanis

相關問題