0

When I'm running this code the file is created, but it is empty although output looks OK

import java.io.IOException;

public class JasonTest {
    public static void main(String[] args) throws IOException {
        Gson gson = new GsonBuilder().setPrettyPrinting().create();
        TestJson tj = new TestJson(13, "kuku");
        gson.toJson(tj, new FileWriter("test.json"));
        System.out.println(gson.toJson(tj));

    }
}

Output:

{
  "num": 13,
  "text": "kuku"
}

Process finished with exit code 0
Progman
  • 16,827
  • 6
  • 33
  • 48
DoronS
  • 347
  • 1
  • 6
  • 12

1 Answers1

1

See this question. You need to close FileWriter (or flush if cannot be closed yet at the moment). So like:

FileWriter fw = new FileWriter("test.json");
gson.toJson(tj, fw);
fw.close();

or better with try/resources:

// Does auto close
try(FileWriter fw = new FileWriter("test.json")) {
    gson.toJson(tj, fw);            
}
pirho
  • 11,565
  • 12
  • 43
  • 70