diff options
Diffstat (limited to 'src/main/persistance')
-rw-r--r-- | src/main/persistance/JsonAble.java | 7 | ||||
-rw-r--r-- | src/main/persistance/JsonUtils.java | 44 |
2 files changed, 51 insertions, 0 deletions
diff --git a/src/main/persistance/JsonAble.java b/src/main/persistance/JsonAble.java new file mode 100644 index 0000000..408cb06 --- /dev/null +++ b/src/main/persistance/JsonAble.java @@ -0,0 +1,7 @@ +package persistance; + +import org.json.JSONObject; + +public interface JsonAble { + public JSONObject serialize(); +} diff --git a/src/main/persistance/JsonUtils.java b/src/main/persistance/JsonUtils.java new file mode 100644 index 0000000..4e11a18 --- /dev/null +++ b/src/main/persistance/JsonUtils.java @@ -0,0 +1,44 @@ +package persistance; + +import org.json.JSONArray; +import org.json.JSONObject; + +import java.io.PrintWriter; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; + +public class JsonUtils { + + /** + * REQUIRES: A valid filepath path, a writeable JSONObject json + * EFFECTS: writes a String to a file + */ + public static void writeToFile(JSONArray json, String path) { + PrintWriter writer; + try { + writer = new PrintWriter(path); + writer.print(json); + writer.close(); + } catch (Exception e) { + System.out.printf("Write to file failed with %s", e.toString()); + } + } + + /** + * REQUIRES: a path to a valid file containing JSONObject-serialized data + * EFFECTS: reads a serialized String into a JSONObject + */ + public static JSONArray readFromFile(String path) { + String content; + JSONArray deread; + try { + content = Files.readString(Paths.get(path)); + deread = new JSONArray(content); + } catch (Exception e) { + System.out.println("Read from file failed with %s"); + deread = new JSONArray(); + } + return deread; + } +} |