Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package cz.vse.java.zavl03.logika;
- import java.io.FileWriter;
- import java.io.IOException;
- import org.json.simple.JSONObject;
- import org.json.simple.parser.JSONParser;
- import java.io.FileNotFoundException;
- import java.io.FileReader;
- import org.json.simple.parser.ParseException;
- /**
- * Kód převzat z: https://howtodoinjava.com/java/library/json-simple-read-write-json-examples/
- *
- * Třída JSONController je určena pro práci s úložištěm.
- */
- public class JSONController {
- private String filePath;
- private JSONObject data;
- /**
- * Konstruktor
- * Ukládá obsah souboru s informaci o uživatelích
- *
- * @param filePath
- */
- public JSONController(String filePath){
- this.filePath = filePath;
- data = readJSON();
- }
- public void updateUserData(Uzivatel uzivatel) {
- JSONObject userDetails = registerUser(uzivatel);
- if(data == null){
- data = new JSONObject();
- }
- data.put(uzivatel.getEmail(), userDetails);
- writeJSON(data);
- }
- /**
- * Uložení do souboru
- * @param userObject
- */
- public void writeJSON(JSONObject userObject) {
- //Write JSON file
- try (FileWriter file = new FileWriter(filePath)) {
- file.write(userObject.toJSONString());
- file.flush();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- public JSONObject registerUser(Uzivatel uzivatel) {
- JSONObject userDetails = new JSONObject();
- userDetails.put("username", uzivatel.getUsername());
- userDetails.put("email", uzivatel.getEmail());
- userDetails.put("password", uzivatel.getHeslo());
- return userDetails;
- }
- public JSONObject readJSON() {
- JSONParser jsonParser = new JSONParser();
- try (FileReader reader = new FileReader(filePath)) {
- //Read JSON file
- Object obj = jsonParser.parse(reader);
- JSONObject userList = (JSONObject) obj;
- return userList;
- } catch (FileNotFoundException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- } catch (ParseException e) {
- e.printStackTrace();
- }
- return null;
- }
- }
RAW Paste Data