Answer the question
In order to leave comments, you need to log in
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); // Зачем указывать тип объекта в конце?
}
}
Answer the question
In order to leave comments, you need to log in
Why read a file through Scanner?
Why use a loop? it is impossible to take and all to read without a cycle?
Why does the line need to pass the file data?
fromJson
we 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?
fromJson
deserializes the JSON read from the Reader (in this case, a string) into an object of the class specified by the second argument. 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 questionAsk a Question
731 491 924 answers to any question