I have json {"name": "John", "tests":["apple"]}
. In my Java code I want to update this json throught gson - add string field to json array and save to file to have this json - {"name": "John", "tests":["apple", "pinapple"]}
. So is there a way how ? Java class for my json look like this:
public class Test{
private String name;
private List<String> tests;
// Getters/Setters
}
Reading json in java like this:
Gson gson = new Gson();
try (Reader reader = new FileReader("D:\\file.json")) {
Test js = gson.fromJson(reader, Test.class);
System.out.println(js.getName());
} catch (IOException e) {
e.printStackTrace();
}
Doing this my new json file is empty:
Gson gson = new Gson();
try (Reader reader = new FileReader("D:\\file.json")) {
Test test = gson.fromJson(reader, Test.class);
System.out.println(test.getName());
test.getTests().add("pinapple");
String newJson = gson.toJson(test);
System.out.println(newJson);
gson.toJson(test, new FileWriter("D:\\file.json"));
} catch (IOException e) {
e.printStackTrace();
}
Test test = gson.fromJson(reader, Test.class);
Once you have your Test
object do:
test.getTests().add("pineapple");
Now you have the pineapple
in your array. You can make your JSON string:
String newJson = gson.toJson(test);
System.out.println(newJson);
or write it back in the same file
gson.toJson(test, new FileWriter("D:\\file.json"));
EDIT : Whole code
String fileName = "D:\\file.json";
Gson gson = new Gson();
Test test = null;
try (Reader reader = new FileReader(fileName)) {
test = gson.fromJson(reader, Test.class);
} catch (IOException e) {
e.printStackTrace();
}
test.getTests().add("pineapple");
String newJson = gson.toJson(test);
System.out.println(newJson);
try (Writer writer = new FileWriter(fileName)) {
gson.toJson(test, writer);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.