如何在 Java 中編寫/建立 JSON 檔案?
JSON 或 JavaScript 物件表示法是一種輕量級、基於文字的開放標準,旨在用於人類可讀的資料交換。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 庫
The JSON-simple 是一個輕量級的庫,用於處理 JSON 物件。使用它,您可以使用 Java 程式讀取或寫入 JSON 文件的內容。
JSON-Simple Maven 依賴項
以下是 JSON-simple 庫的 Maven 依賴項:
<dependencies> <dependency> <groupId>com.googlecode.json-simple</groupId> <artifactId>json-simple</artifactId> <version>1.1.1</version> </dependency> </dependencies>
將此貼上到 "pom.xml" 檔案末尾的 <dependencies> </dependencies> 標記內。(在 </project> 標記之前)
示例
要使用 Java 程式建立 JSON 文件:
- 例項化 json-simple 庫的 JSONObject 類。
//Creating a JSONObject object JSONObject jsonObject = new JSONObject();
- 使用 JSONObject 類的 put() 方法插入所需的鍵值對。
jsonObject.put("key", "value");
- 使用 FileWriter 類將建立的 JSON 物件寫入檔案,如下所示:
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 檔案的內容,您可以看到建立的資料如下所示:
廣告