Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Java

Cách tạo/g ghi file JSON bằng Java

JSON (JavaScript Object Notation) là tiêu chuẩn mở dựa trên văn bản nhẹ, thiết kế cho trao đổi dữ liệu dễ đọc. Quy ước JSON được lập trình viên biết đến: C, C++, Java, Python, Perl, v.v.

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 tạo file JSON

  1. Khởi tạo JSONObject.
    JSONObject jsonObject = new JSONObject();
  2. Chèn key-value bằng put().
    jsonObject.put("key", "value");
  3. Ghi JSON object vào file dùng FileWriter.
    FileWriter file = new FileWriter("E:/output.json"); 
    file.write(jsonObject.toJSONString()); 
    file.close();

Ví dụ hoàn chỉnh

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); 
    } 
}

Kết quả đầu ra

JSON file created: { 
    "First_Name":"Shikhar", 
    "Place_Of_Birth":"Delhi", 
    "Last_Name":"Dhawan", 
    "Country":"India", 
    "ID":"1", 
    "Date_Of_Birth":"1981-12-05" 
}

Lưu ý: Thư viện Jackson hoặc Gson phổ biến hơn cho các dự án thực tế do hiệu năng tốt hơn, hỗ trợ mapping object tự động (POJO ↔ JSON).