JSON มาตรฐานข้อมูลข้อความเบา ใช้ json-simple library อ่าน/เขียนได้
Maven Dependency
<dependency>
<groupId>com.googlecode.json-simple</groupId>
<artifactId>json-simple</artifactId>
<version>1.1.1</version>
</dependency>
ไฟล์ JSON ตัวอย่าง (sample.json)
{
"ID": "1",
"First_Name": "Shikhar",
"Last_Name": "Dhawan",
"Date_Of_Birth": "1981-12-05",
"Place_Of_Birth": "Delhi",
"Country": "India"
}
ขั้นตอนอ่าน JSON File
- สร้าง JSONParser
- Parse ด้วย parse(FileReader) ได้ JSONObject
- ดึงค่าแต่ละ key ด้วย get("key_name") cast เป็น String
ตัวอย่างโค้ดเต็ม
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
public class ReadingJSON {
public static void main(String args[]) {
JSONParser jsonParser = new JSONParser();
try {
JSONObject jsonObject = (JSONObject) jsonParser.parse(new FileReader("E:/sample.json"));
String id = (String) jsonObject.get("ID");
String first_name = (String) jsonObject.get("First_Name");
String last_name = (String) jsonObject.get("Last_Name");
String date_of_birth = (String) jsonObject.get("Date_Of_Birth");
String place_of_birth = (String) jsonObject.get("Place_Of_Birth");
String country = (String) jsonObject.get("Country");
System.out.println("Contents of the JSON are: ");
System.out.println("ID: " + id);
System.out.println("First name: " + first_name);
System.out.println("Last name: " + last_name);
System.out.println("Date of birth: " + date_of_birth);
System.out.println("Place of birth: " + place_of_birth);
System.out.println("Country: " + country);
} catch (FileNotFoundException | IOException | ParseException e) {
e.printStackTrace();
}
}
}
ผลลัพธ์
Contents of the JSON are:
ID: 1
First name: Shikhar
Last name: Dhawan
Date of birth: 1981-12-05
Place of birth: Delhi
Country: India
จุดสำคัญ
- json-simple คืน Object ต้อง cast (String) ทุกครั้ง
- Key ต้องตรงกับ JSON ทุกตัว (case-sensitive)
- ใช้ try-catch ครอบ 3 exception หลัก
- สำหรับ JSON ซับซ้อน (nested object/array) ใช้ JSONObject/JSONArray ซ้อนกัน
ทางเลือก Library อื่น
- Jackson - ObjectMapper.readValue() map ไป POJO โดยตรง
- Gson - gson.fromJson() แปลงเป็น Object แบบ type-safe
- JSON-P - JsonReader, JsonObject แบบ streaming