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