JSON (JavaScript Object Notation) มาตรฐานข้อมูลข้อความเบา สำหรับแลกเปลี่ยนข้อมูล อ่านง่าย เข้าใจง่าย
ตัวอย่าง JSON Document
{
"book": [
{ "id": "01", "language": "Java", "edition": "third", "author": "Herbert Schildt" },
{ "id": "07", "language": "C++", "edition": "second", "author": "E.Balagurusamy" }
]
}
JSON-Simple Maven Dependency
<dependency>
<groupId>com.googlecode.json-simple</groupId>
<artifactId>json-simple</artifactId>
<version>1.1.1</version>
</dependency>
ขั้นตอนสร้าง JSON File
- สร้าง JSONObject
- ใส่ key-value ด้วย put()
- เขียนไฟล์ด้วย FileWriter
ตัวอย่างโค้ดเต็ม
import java.io.FileWriter;
import java.io.IOException;
import org.json.simple.JSONObject;
public class CreatingJSONDocument {
public static void main(String args[]) {
JSONObject jsonObject = new JSONObject();
jsonObject.put("ID", "1");
jsonObject.put("First_Name", "Shikhar");
jsonObject.put("Last_Name", "Dhawan");
jsonObject.put("Date_Of_Birth", "1981-12-05");
jsonObject.put("Place_Of_Birth", "Delhi");
jsonObject.put("Country", "India");
try {
FileWriter file = new FileWriter("E:/output.json");
file.write(jsonObject.toJSONString());
file.close();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("JSON file created: " + jsonObject);
}
}
ผลลัพธ์
JSON file created: {
"First_Name": "Shikhar",
"Place_Of_Birth": "Delhi",
"Last_Name": "Dhawan",
"Country": "India",
"ID": "1",
"Date_Of_Birth": "1981-12-05"
}
ข้อดีของ json-simple
- เบา (lightweight) ไม่มี dependency อื่น
- API เรียบง่าย ใช้งานง่าย
- รองรับทั้ง read และ write JSON
ทางเลือกอื่น
- Jackson - เร็ว, ฟีเจอร์มาก, มาตรฐานอุตสาหกรรม
- Gson - Google ทำ, ใช้ง่าย, รองรับ POJO mapping
- JSON-P (javax.json) - EE standard, อยู่ใน Java EE/Jakarta EE