我一直在使用预订系统的应用程序,我有生成json的问题并将其发送到服务器。服务器抓住这个json
"buy":{
"583":[
{
"title":"Mr",
"nama_depan":"Mulia Rifai Aroyan",
"nama_belakang":"",
"tanggal_lahir":"0000-0-0",
"nationality":"Indonesia",
"identitas":"identitas",
"kelas_id":"254",
"kelas":"B",
"harga":"60000",
"seat":""
}
],
"584":[
{
"title":"Mr",
"nama_depan":"Mulia Rifai Aroyan",
"nama_belakang":"",
"tanggal_lahir":"0000-0-0",
"nationality":"Indonesia",
"identitas":"identitas",
"kelas_id":"254",
"kelas":"B",
"harga":"60000",
"seat":""
}
]
}
我创建生成的json如下:
final JSONObject buy_child = new JSONObject();
final JSONArray buy = new JSONArray();
final JSONObject detail = new JSONObject();
for (int i=0;i<list_id_content.size();i++)
{
detail.put("title",gelar);
detail.put("nama_depan",nama_depan);
detail.put("nama_belakang",nama_belakang);
detail.put("tanggal_lahir",tanggal_lahir);
detail.put("nationality",nationality);
detail.put("identitas",identitas);
detail.put("kelas_id",id_event);
detail.put("kelas",kelas);
detail.put("harga",total_harga_pertiket);
detail.put("seat","");
buy.put(detail);
buy_child.put(id_event_content2,buy);
}
但它似乎只生成具有相同值(最后一个值)的json
我怎么能像这样生成json并获得循环中的所有值?
谢谢
编辑:如果我把JSONObject detail = new JSONObject();在循环内部,它会给我这个
答案 0 :(得分:0)
将JSONObject detail = new JSONObject();
放在for循环中。
然后将buy.put(detail);
放在循环的末尾(但在里面)。
你现在只获得最后一个,因为buy.put在for循环之外。
答案 1 :(得分:0)
试试这个
final JSONObject buy_child = new JSONObject();
final JSONArray buy;
for (int i=0;i<list_id_content.size();i++)
{
buy= new JSONArray();
final JSONObject detail = new JSONObject();
detail.put("title",gelar);
detail.put("nama_depan",nama_depan);
detail.put("nama_belakang",nama_belakang);
detail.put("tanggal_lahir",tanggal_lahir);
detail.put("nationality",nationality);
detail.put("identitas",identitas);
detail.put("kelas_id",id_event);
detail.put("kelas",kelas);
detail.put("harga",total_harga_pertiket);
detail.put("seat","");
buy.put(detail);
}
buy_child.put(id_event_content2,buy);