I
I
Important_question2021-04-29 19:18:28
Java
Important_question, 2021-04-29 19:18:28

How to check if Json file is correct?

I am trying to process json syntax errors in more detail, so that when reading a file and in the absence of any field, the program asks the user if he is ready to add
this field or skip this object and load the remaining objects in the file into the collection.
Let's say we removed the name field from the file (that is, the entire "name": "P3111"). And it is necessary that the program issues You have an error in the name field in one of the objects. Do you want to add it or skip loading this object? (true/false)
My method reader(json reader)

/**
     * Чтение коллекции из файла
     *
     * @return коллекция, которая была считана из файла
     */
    public PriorityQueue<StudyGroup> readCollection() {
        if (file!= null) {
            if (file.exists() & !file.canRead()) {
                System.out.println("\u001B[37m" + "\u001B[31m" + "Недостаточно прав для чтения данных из файла. Добавьте права на чтение и запустите программу вновь" + "\u001B[31m" + "\u001B[37m");
                System.exit(0);
            }
            try (FileReader fileScanner= new FileReader(file)) {
                BufferedInputStream reader= new BufferedInputStream(new FileInputStream((file)));
                Type collectionType = new TypeToken<PriorityQueue<StudyGroup>>(){}.getType();
                PriorityQueue<StudyGroup> collection = gson.fromJson(fileScanner, collectionType);
                reader.readAllBytes();
                System.out.println("\u001B[37m" + "\u001B[33m" + "Коллекция успешно загружена!" + "\u001B[33m" + "\u001B[37m");
                if (collection == null) return new PriorityQueue<>();
                return collection;
            } catch (FileNotFoundException e) {
                System.err.println("Файл с таким именем не найден :(");

            } catch (IOException e) {
                System.err.println("Ошибка ввода-вывода");

            } catch (JsonSyntaxException e) {
                System.err.println("Формат файла не удовлетворяет условию");
            }
           catch (RuntimeException e){
               Messages.normalMessageOutput("\u001B[37m" + "\u001B[33m"+"Файл написан с ошибкой, перепроверьте файл и запустите программу снова"+ "\u001B[33m" + "\u001B[37m");
           }
        } else
            System.out.println("\u001B[37m" + "\u001B[31m" + "Системная переменная с загрузочным файлом не найдена!" + "\u001B[31m" + "\u001B[37m");
        return new PriorityQueue<>();

    }

json file
[{"id":4229754249302793379,"name":"P3111","coordinates":{"x":32,"y":-360.0},"creationDate":{"date":{"year":2021,"month":4,"day":27},"time":{"hour":10,"minute":41,"second":15,"nano":506122400}},"studentsCount":32,"expelledStudents":5,"formOfEducation":"DISTANCE_EDUCATION","semesterEnum":"FIRST","groupAdmin":{"name":"Маша","passportID":"123","eyeColor":"BLACK","hairColor":"BLACK","nationality":"USA"}},{"id":5576486070722418065,"name":"P3111","coordinates":{"x":32,"y":-360.0},"creationDate":{"date":{"year":2021,"month":4,"day":27},"time":{"hour":10,"minute":41,"second":24,"nano":974652600}},"studentsCount":32,"expelledStudents":5,"formOfEducation":"DISTANCE_EDUCATION","semesterEnum":"FIRST","groupAdmin":{"name":"Маша","passportID":"123","eyeColor":"BLACK","hairColor":"BLACK","nationality":"USA"}}]

Answer the question

In order to leave comments, you need to log in

1 answer(s)
O
Orkhan, 2021-05-04
Hasanly @azerphoenix

Good afternoon.
To check the correctness of the json file, you first need to read it and deserialize it.
You can try to do the following:
1) Read the json into the pojo and check the fields for null. If one of the fields is null, then ask the user to enter a new value for that field.
2) Or you can also read json using jackson. And there, if you did not add an annotation @JsonInclude(Include.NON_NULL)to the class, then the corresponding exception will be thrown during deserialization. So, you can catch this exception and display a message for the user.
Here are some ideas...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question