import
java.io.IOException;
import
org.json.simple.JSONArray;
import
org.json.simple.JSONObject;
其中,
json-simple
库用于解析和生成JSON,而
FileWriter
则用于将JSON写入文件。
创建JSONObject和JSONArray对象
在将JSON写入文件之前,需要先创建一个JSONObject和一个JSONArray对象。
JSONObject jsonObject = new JSONObject();
JSONArray jsonArray = new JSONArray();
JSONObject用于表示一个JSON对象,而JSONArray用于表示一个JSON数组。
添加数据到JSONObject和JSONArray
向JSONObject中添加数据的方法是使用 put
方法,例如:
jsonObject.put("name", "John Doe");
jsonObject.put("age", 30);
向JSONArray中添加数据的方法是使用 add
方法,例如:
jsonArray.add("apple");
jsonArray.add("banana");
将JSONObject添加到JSONArray中
如果需要将一个JSONObject添加到一个JSONArray中,可以直接使用 add
方法,例如:
jsonArray.add(jsonObject);
将JSONArray写入文件
使用 FileWriter
将JSONArray写入文件的方法如下:
try (FileWriter file = new FileWriter("output.json")) {
file.write(jsonArray.toJSONString());
} catch (IOException e) {
e.printStackTrace();
其中,toJSONString()
方法用于将JSONArray转换成字符串,然后写入文件。
完整的代码示例:
import java.io.FileWriter;
import java.io.IOException;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
public class JSONWriter {
public static void main(String[] args) {
JSONObject jsonObject = new JSONObject();
JSONArray jsonArray = new JSONArray();
jsonObject.put("name", "John Doe");
jsonObject.put("age", 30);
jsonArray.add("apple");
jsonArray.add("banana");
jsonArray.add(jsonObject);
try (FileWriter file = new FileWriter("output.json")) {
file.write(jsonArray.toJSONString());
} catch (IOException e) {
e.printStackTrace();
注意,为了简化代码,这个例子使用了try-with-resources语句,它会自动关闭文件句柄。