diff options
author | j-james | 2022-10-29 04:22:06 +0000 |
---|---|---|
committer | j-james | 2022-10-29 04:22:06 +0000 |
commit | 106a0fe85effd27f8da28d17cf1053d5c50cd5fc (patch) | |
tree | a5f706008452fb30091e59752576a09aaf6ca390 /src/main/persistance | |
parent | 9a512732accf6869764fedc7c5d1abad57c6cb28 (diff) |
Implement functionality for P2
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; + } +} |