2015-06-10 116 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

相关问题