JSON หรือ JavaScript Object Notation เป็นมาตรฐานเปิดแบบข้อความที่มีน้ำหนักเบาซึ่งออกแบบมาสำหรับการแลกเปลี่ยนข้อมูลที่มนุษย์สามารถอ่านได้ โปรแกรมเมอร์รู้จักอนุสัญญาที่ใช้โดย JSON ซึ่งรวมถึง C, C++, Java, Python, Perl เป็นต้น ตัวอย่างเอกสาร JSON −
{
"book": [
{
"id": "01",
"language": "Java",
"edition": "third",
"author": "Herbert Schildt"
},
{
"id": "07",
"language": "C++",
"edition": "second",
"author": "E.Balagurusamy"
}
]
} ไลบรารี Json-simple
json-simple เป็นไลบรารี่น้ำหนักเบาซึ่งใช้ในการประมวลผลอ็อบเจ็กต์ JSON คุณสามารถอ่านหรือเขียนเนื้อหาของเอกสาร JSON โดยใช้โปรแกรม Java ได้
JSON-การพึ่งพา maven อย่างง่าย
ต่อไปนี้คือการพึ่งพา maven สำหรับไลบรารีแบบง่าย JSON -
<dependencies> <dependency> <groupId>com.googlecode.json-simple</groupId> <artifactId>json-simple</artifactId> <version>1.1.1</version> </dependency> </dependencies>
วางสิ่งนี้ด้วยในแท็ก
ตัวอย่าง
ในการสร้างเอกสาร JSON โดยใช้โปรแกรม Java -
- สร้างตัวอย่างคลาส JSONObject ของไลบรารี json-simple
//Creating a JSONObject object JSONObject jsonObject = new JSONObject();
- แทรกคู่คีย์-ค่าที่จำเป็นโดยใช้ put() วิธีการของ JSONObject คลาส.
jsonObject.put("key", "value"); - เขียนวัตถุ JSON ที่สร้างขึ้นลงในไฟล์โดยใช้คลาส FileWriter เป็น -
FileWriter file = new FileWriter("E:/output.json");
file.write(jsonObject.toJSONString());
file.close(); โปรแกรม Java ที่ตามมาจะสร้างวัตถุ JSON และเขียนลงในไฟล์ชื่อ output.json .
ตัวอย่าง
import java.io.FileWriter;
import java.io.IOException;
import org.json.simple.JSONObject;
public class CreatingJSONDocument {
public static void main(String args[]) {
//Creating a JSONObject object
JSONObject jsonObject = new JSONObject();
//Inserting key-value pairs into the json object
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) {
// TODO Auto-generated catch block
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 คุณจะเห็นข้อมูลที่สร้างขึ้นเป็น -
