Library org.json.simple ให้อ่านและเขียน JSON data ใน Java ได้ กล่าวคือ สามารถ encode และ decode JSON object ได้ Package org.json.simple มีคลาสสำคัญเช่น JSONValue, JSONObject, JSONArray, JsonString, JsonNumber ต้องติดตั้งไฟล์ json-simple.jar เพื่อรันโปรแกรม JSON
ในขณะที่ library org.json มีคลาสสำหรับ parse JSON ใน Java ยังแปลงระหว่าง JSON และ XML, HTTP headers, Cookies, และ CDL ได้ Package org.json มีคลาสสำคัญเช่น JSONObject, JSONTokener, JSONWriter, JSONArray, CDL, Cookie, CookieList ต้องติดตั้ง json.jar เพื่อรันโปรแกรม
ตัวอย่าง org.json.simple package
import org.json.simple.JSONObject;
public class SimpleJsonTest {
public static void main(String[] args) {
JSONObject jsonObj = new JSONObject();
jsonObj.put("empName", "Raja");
jsonObj.put("employeeId", "115");
jsonObj.put("age", "30");
System.out.println(jsonObj.toJSONString());
}
}
ผลลัพธ์
{"empName":"Raja","employeeId":"115","age":"30"}
ตัวอย่าง org.json package
import org.json.*;
public class JSONTest {
public static void main(String args[]) throws JSONException {
String json = "{" + "Name : Jai," + "Age : 25, " + "Salary: 25000.00 " + "}";
JSONObject jsonObj = new JSONObject(json);
System.out.println(jsonObj.toString());
}
}
ผลลัพธ์
{"Salary":25000,"Age":25,"Name":"Jai"}
ตารางเปรียบเทียบคุณสมบัติหลัก
| คุณสมบัติ | org.json.simple | org.json |
|---|---|---|
| Maven Central Name | json-simple (com.googlecode.json-simple) | org.json (org.json:json) |
| License | Apache 2.0 | JSON License (มีข้อจำกัด "The Software shall be used for Good, not Evil") |
| JSON Parsing | รองรับ (JSONParser) | รองรับ (JSONTokener, JSONObject constructor) |
| JSON Generation | รองรับ (JSONObject, JSONArray) | รองรับ (JSONObject, JSONArray, JSONWriter) |
| XML Conversion | ไม่รองรับ | รองรับ (XML.toString(), XML.toJSONObject()) |
| HTTP/Cookie/CDL | ไม่รองรับ | รองรับ (Cookie, CookieList, CDL, HTTP) |
| Streaming API | ไม่รองรับ | ไม่รองรับ (ทั้งคู่เป็น Object Model) |
| Performance | เร็วกว่าเล็กน้อย | ช้ากว่าเล็กน้อย |
| Maintenance Status | Active (forks available) | Low maintenance (original by Douglas Crockford) |
คำแนะนำการเลือกใช้
- org.json.simple - เหมาะสำหรับ JSON parsing/generation พื้นฐาน ไม่ต้องการ XML/HTTP features
- org.json - เหมาะเมื่อต้องการ XML conversion, HTTP header parsing, Cookie handling, หรือ CDL (CSV) conversion
- Alternative ทันสมัยกว่า: Jackson, Gson, JSON-B (มาตรฐาน EE) - มีประสิทธิภาพดีกว่า Streaming API และ features มากกว่า
สรุป
ทั้งสอง library เป็น legacy libraries สำหรับ JSON processing ใน Java org.json.simple เน้น simplicity และ performance org.json เน้น features ครอบคลุม (XML, HTTP, Cookies) สำหรับโปรเจกต์ใหม่ แนะนำให้ใช้ Jackson หรือ Gson แทน