JSON (JavaScript Object Notation) là tiêu chuẩn mở dựa trên văn bản nhẹ cho trao đổi dữ liệu dễ đọc.
Tài liệu JSON mẫu
{
"book": [
{ "id": "01", "language": "Java", "edition": "third", "author": "Herbert Schildt" },
{ "id": "07", "language": "C++", "edition": "second", "author": "E.Balagurusamy" }
]
}
Thư viện json-simple
Thư viện nhẹ xử lý đối tượng JSON. Cho phép đọc/ghi tài liệu JSON bằng Java.
Maven dependency json-simple
<dependencies>
<dependency>
<groupId>com.googlecode.json-simple</groupId>
<artifactId>json-simple</artifactId>
<version>1.1.1</version>
</dependency>
</dependencies>
Các bước đọc file JSON
- Khởi tạo JSONParser.
JSONParser jsonParser = new JSONParser();
- Phân tích nội dung bằng parse().
JSONObject jsonObject = (JSONObject) jsonParser.parse(new FileReader("E:/players_data.json")); - Lấy giá trị theo key bằng get().
String value = (String) jsonObject.get("key_name");
Ví dụ hoàn chỉnh
File sample.json:
{
"ID": "1",
"First_Name": "Shikhar",
"Last_Name": "Dhawan",
"Date_Of_Birth": "1981-12-05",
"Place_Of_Birth": "Delhi",
"Country": "India"
}
Chương trình đọc:
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);
System.out.println(" ");
} catch (FileNotFoundException | IOException | ParseException e) {
e.printStackTrace();
}
}
}
Kết quả đầu ra
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
Lưu ý: Trong thực tế, Jackson (ObjectMapper) hoặc Gson thường được dùng hơn nhờ mapping tự động POJO, hiệu năng tốt, hỗ trợ streaming API.