V
V
vitya_brodov2021-01-16 22:03:34
Java
vitya_brodov, 2021-01-16 22:03:34

Why read json through Scanner?

Hello!
there is a method that reads data from a json file:
I myself tried to understand why to do this, but it did not work out.
The question itself is in the comments of the code:

public class JsonReader {
    private final Gson gson = new GsonBuilder().setPrettyPrinting().create();

    public Trucks[] reader(){
        String fromJson = "";
        try (FileReader fileReader = new FileReader("./trucks.json");
                Scanner sc = new Scanner(fileReader))  // Зачем считывать файл через Scanner?
        {
            while (sc.hasNextLine()){ // Зачем использовать цикл? нельзя взять и всю прочитать без цикла?
               fromJson += sc.nextLine(); // Зачем строке происваевать данные файла?
            }
        }catch (IOException exception){
            exception.printStackTrace();
        }
        return gson.fromJson(fromJson, Trucks[].class); // Зачем указывать тип объекта в конце?
    }
}


ps I would be grateful if you throw off useful links, etc. for json in java

Answer the question

In order to leave comments, you need to log in

2 answer(s)
E
Erik Mironov, 2021-01-16
@vitya_brodov

Why read a file through Scanner?

With the Scanner class, you can read data from a file just like you can with BufferedReader, BufferedInputStream, and other classes that can read file data. Why Scanner was used here is known only to the one who wrote this class, because there are more suitable classes for such operations.
Why use a loop? it is impossible to take and all to read without a cycle?

Because this is a generic class, and in a real work situation you wouldn't know what size files to read with this method, it's much better to use loops and read the file line by line. You can read the whole file, but it will be terribly slow on large files.
Why does the line need to pass the file data?

In a variable, fromJsonwe store the read data, and since JSON is a regular set of text, using the String type is more than suitable for this operation. You can also use collections or arrays for this.
Why specify the type of the object at the end?

The method fromJsondeserializes the JSON read from the Reader (in this case, a string) into an object of the class specified by the second argument.
Link to class spec
https://www.javadoc.io/doc/com.google.code.gson/gs...

A
Andrey Ezhgurov, 2021-01-16
@eandr_67

JSON is just text. And reading JSON is no different than reading any text file.
Using Scanner is one way to read a text file. In this case, not the best way.
For example, here https://javadevblog.com/kak-schitat-fajl-v-string-... shows 4 different ways to read a text file into a String variable.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question