如何在 Java 中将 JSON 字符串添加到现有的 JSON 文件?
javajsonobject oriented programmingprogramming更新于 2025/7/17 12:28:17
Gson 是 Java 的一个 JSON 库,可用于生成 JSON。在初始步骤中,我们可以读取 JSON 文件并解析为 Java 对象,然后需要将 Java 对象类型转换为 JSonObject 并解析为 JsonArray。然后迭代此 JSON 数组以打印 JsonElement。我们可以创建一个 JsonWriter 类,将 JSON 编码值一次一个标记地写入流。最后,可以将新的 JSON 字符串写入现有的 json 文件。
示例
import java.io.*;
import java.util.*;
import com.google.gson.*;
import com.google.gson.stream.*;
import com.google.gson.annotations.*;
public class JSONFilewriteTest {
public static String nameRead;
public static void main(String[] args) {
try {
JsonParser parser = new JsonParser();
Object obj = parser.parse(new FileReader("employee1.json"));
JsonObject jsonObject = (JsonObject) obj;
System.out.println("The values of employee1.json file:\n" + jsonObject);
JsonArray msg = (JsonArray)jsonObject.get("emps");
Iterator<JsonElement> iterator = msg.iterator();
while(iterator.hasNext()) {
nameRead = iterator.next().toString();
System.out.println(nameRead);
}
Name name = new Name();
name.setName("Vamsi");
Gson gson = new Gson();
String json = gson.toJson(name);
FileWriter file = new FileWriter("employee1.json", false);
JsonWriter jw = new JsonWriter(file);
iterator = msg.iterator();
Employees emps = new Employees();
while(iterator.hasNext()) {
emps.addEmployee(gson.fromJson(iterator.next().toString(), Name.class));
}
emps.addEmployee(name);
gson.toJson(emps, Employees.class, jw);
file.close();
System.out.println("data added to an existing employee1.json file successfully");
} catch(Exception e) {
e.printStackTrace();
}
}
}
// Name classclass Name {
@Expose private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
// Employees classclass Employees {
@Expose List<Name> emps = new ArrayList<>();
public List<Name> getEmployees() {
return emps;
}
public void addEmployee(Name name) {
this.emps.add(name);
}
}
输出
The values of employee1.json file:
{"emps":[{"name":"Adithya"},{"name":"Jai"}]}
{"name":"Adithya"}
{"name":"Jai"}
data added to an existing employee1.json file successfully
employee1.json file
相关文章
有用资源
java 参考教程 - 该教程包含有关 java 的更多信息:https://www.cainiaomax.com/java/

