Advertisement
xickoh

json

Jul 11th, 2021
995
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.42 KB | None | 0 0
  1. public static void saveTestResult(int nif, boolean result) {
  2.  
  3.         JSONParser parser = new JSONParser();
  4.         try {
  5.             File file = new File("data/tests.json");
  6.  
  7.             JSONArray tests = new JSONArray();
  8.  
  9.             if (file.length() != 0) {
  10.                 Object obj = parser.parse(new FileReader(file));
  11.                 JSONObject jsonObject = (JSONObject) obj;
  12.                 tests = (JSONArray) jsonObject.get("test");
  13.  
  14.             }
  15.  
  16.             JSONObject test = new JSONObject();
  17.  
  18.             Date date = new Date();
  19.             SimpleDateFormat formattedDate = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
  20.  
  21.             test.put("nif", nif);
  22.             test.put("result", result);
  23.             test.put("date", formattedDate.format(date));
  24.  
  25.             tests.add(test);
  26.  
  27.             JSONObject allTests = new JSONObject();
  28.             allTests.put("test", tests);
  29.  
  30.             try ( FileWriter fileWriter = new FileWriter("data/tests.json")) {
  31.                 fileWriter.write(allTests.toJSONString());
  32.             } catch (Exception e) {
  33.             }
  34.         } catch (FileNotFoundException ex) {
  35.             System.out.println("Ficheiro não encontrado");
  36.         } catch (IOException e) {
  37.             System.out.println("Não existem");
  38.         } catch (ParseException ex) {
  39.             System.out.println("Não foi possível validar o ficheiro de utilizadores");
  40.         }
  41.  
  42.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement