Ho creato un file Json in cui volevo scrivere oggetto java di scrittura come elemento Array. Sto usando Jackson.Come scrivere JSON Array su file utilizzando jackson
try{
String json;
String phyPath = request.getSession().getServletContext().getRealPath("/");
String filepath = phyPath + "resources/" + "data.json";
File file = new File(filepath);
if (!file.exists()) {
System.out.println("pai nai");
file.createNewFile();
}
json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(story);
Files.write(new File(filepath).toPath(), Arrays.asList(json), StandardOpenOption.APPEND);
}
Questo non è esattamente quello che voglio .it crea dati come
{
"storyTitle" : "ttt",
"storyBody" : "tttt",
"storyAuthor" : "tttt"
}
{
"storyTitle" : "a",
"storyBody" : "a",
"storyAuthor" : "a"
}
Ho solo bisogno di creare un array di JSON in cui aggiungo oggetto Java, i dati dovrebbero essere come questo
[{
"storyTitle" : "ttt",
"storyBody" : "tttt",
"storyAuthor" : "tttt"
}
,{
"storyTitle" : "a",
"storyBody" : "a",
"storyAuthor" : "a"
}]
suggerimento non correlato: non è necessario creare il file se non esiste. Basta scrivere ad esso. – Henry
'writeValueAsString (story);' puoi mostrare il codice che definisce cosa 'story' è? – PDStat
Ho ottenuto il metodo di scrittura che ho scritto come Array – Sayem