在本 Java 教程中,我们将使用 Java 在 file
中编写 JSON objects
和 JSON Array
。 要使用 Java 程序创建 JSON 文件,我们需要在项目构建路径中添加 JSON.simple
jar。
下载 JSON.simple 或在您的项目中添加 maven/gradle 依赖项。
pom.xml
<dependency>
<groupId>com.googlecode.json-simple</groupId>
<artifactId>json-simple</artifactId>
<version>1.1.1</version>
</dependency>
**检查这个:**如何在Java中解析JSON
build.gradle
compile group: 'com.googlecode.json-simple', name: 'json-simple', version: '1.1.1'
现在创建包 org.json.simple.JSONObject
的 JSONObject 类的对象,并使用 put(K,V)
方法添加值,其中 K = ObjectName 和 V = ObjectValue
JSONObject jsonObject = new JSONObject();
jsonObject.put("website", "www.websparrow.org");
同理,创建包org.json.simple.JSONArray
的JSONArray类的对象
JSONArray jsonArray = new JSONArray();
jsonArray.add("Java");
jsonObject.put("technology", jsonArray);
最后,使用 FileWriter
类将 JSONObject
写入文件。
JsonWriteExample.java
package org.websparrow;
import java.io.FileWriter;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
public class JsonWriteExample {
public static void main(String[] args) {
JSONObject jsonObject = new JSONObject();
//JSON object and values
jsonObject.put("name", "Atul Rai");
jsonObject.put("occupation", "Blogger");
jsonObject.put("location", "India");
jsonObject.put("website", "www.websparrow.org");
//JSON array and values
JSONArray jsonArray = new JSONArray();
jsonArray.add("Java");
jsonArray.add("Struts");
jsonArray.add("jQuery");
jsonArray.add("JavaScript");
jsonArray.add("Database");
jsonObject.put("technology", jsonArray);
// writing the JSONObject into a file(info.json)
try {
FileWriter fileWriter = new FileWriter("info.json");
fileWriter.write(jsonObject.toJSONString());
fileWriter.flush();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(jsonObject);
}
}
输出:
要检查对象是否在文件中打包,请转到文件位置并打开文件(info.json
)。
{
"website":"www.websparrow.org",
"occupation":"Blogger",
"name":"Atul Rai",
"location":"India",
"technology":["Java","Struts","jQuery","JavaScript","Database"]
}
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://www.websparrow.org/java/how-to-write-json-object-to-file-in-java
内容来源于网络,如有侵权,请联系作者删除!