0

I need to save objects in one file. I use Gson library. Writing to file is easy, but reading is complicated. I read whole file char by char, but this solution is inefficient. How to read only one JSON string? I have no idea how to do it better.

File file = new File(getContext().getFilesDir(), "slovicka.json");
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
    char s;
    char z = '{';
    char z2 = '}';
    int zavorky = 0;
    String j = "";
    p = 0;
    while (true) {
        s = (char) br.read();
        if (s == z) {
            zavorky++;
        }
        if (s == z2) {
            zavorky--;
        }
        j = j + s;
        if (zavorky == 0) {
            Gson gson = new Gson();
            SlovickoS slovos = gson.fromJson(j, SlovickoS.class);
            list.add(slovo);
            j = "";

        }
        
    }
} catch (Exception e) {
    System.out.println("Chyba při čtení ze souboru.");
}
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
BIBI
  • 11
  • 2
    Does this answer your question? [how to parse JSON file with GSON](https://stackoverflow.com/questions/29965764/how-to-parse-json-file-with-gson) – Marcono1234 Mar 30 '22 at 14:39

1 Answers1

0

You can use a JsonReader with a FileReader.

JsonReader reader = new JsonReader(new FileReader(filename));
SlovickoS slovos = gson().fromJson(reader, SlovickoS.class); 
list.add(slovos);
  • You should close the `FileReader` (ideally with a try-with-resources), and provide an explicit charset to the `FileReader` constructor (e.g. [`StandardCharsets.UTF_8`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/nio/charset/StandardCharsets.html#UTF_8)) to avoid being dependent on the OS charset (might not matter on Android because it always uses UTF-8), or use [`Files.newBufferedReader(Path)`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/nio/file/Files.html#newBufferedReader(java.nio.file.Path)). – Marcono1234 Mar 30 '22 at 15:06