การสร้าง json ใน java ทั้งแบบ array [“aaa”, “bbb”, “ccc”] และ object {“aaa”:”bbb”, “ccc”:”ddd”, “eee”:”fff”} ทำได้ง่ายๆ
สร้าง json array[code language=”java” title=”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);
}[/code]
รวมร่าง[code language=”java” title=”add json array”]json.add( { JSONArray ที่ต้องการรวม } );[/code]
สร้าง json object[code language=”java” title=”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);
}[/code]
รวมร่าง[code language=”java” title=”json to string”]json.put( {index ที่ต้องการ}, { JSONArray ที่ต้องการรวม } );[/code]
แปลงเป็น string เพื่อใช้อย่างอื่น[code language=”java” title=”json to string”]json.toString()[/code]
อ่านเพิ่มเติม JoGet: Bean Shell Create Json
About the author