การสร้าง json ใน java ทั้งแบบ array [“aaa”, “bbb”, “ccc”] และ object {“aaa”:”bbb”, “ccc”:”ddd”, “eee”:”fff”} ทำได้ง่ายๆ
สร้าง json array
import org.json.simple.JSONArray;
JSONArray json = new JSONArray();
while (rs.next()) {
JSONObject item = new JSONArray();
item.add(rs.getObject("appId"));
item.add(rs.getObject("appVersion"));
item.add(rs.getObject("name"));
json.add(item);
}
รวมร่าง
json.add( { JSONArray ที่ต้องการรวม } );
สร้าง json object
import org.json.simple.JSONObject;
JSONObject json = new JSONObject();
while (rs.next()) {
JSONObject item = new JSONObject();
item.put("appVersion", rs.getObject("appVersion"));
item.put("name", rs.getObject("name"));
json.put(rs.getObject("appId"), item);
}
รวมร่าง
json.put( {index ที่ต้องการ}, { JSONArray ที่ต้องการรวม } );
แปลงเป็น string เพื่อใช้อย่างอื่น
json.toString()
อ่านเพิ่มเติม JoGet: Bean Shell Create Json