RuneHive-Tarnish
Neural OSRS Enhancement Framework
Loading...
Searching...
No Matches
JsonSaver.java
1package com.osroyale.util.parser;
2
3import com.google.common.base.Preconditions;
4import com.google.gson.Gson;
5import com.google.gson.GsonBuilder;
6import com.google.gson.JsonArray;
7import com.google.gson.JsonObject;
8
9import java.io.FileWriter;
10
45
46* A util class used for constructing and writing {@code JSON} files.
47 * <p>
48 * <p>
49 * And an example of usage:
50 *
51 * <pre>
52 * JsonSaver json = new JsonSaver();
53 *
54 * for (Player player : players) {
55 * json.current().addProperty(&quot;name&quot;, player.getUsername());
56 * json.current().addProperty(&quot;value1&quot;, 1);
57 * json.current().addProperty(&quot;value2&quot;, true);
58 * json.split();
59 * }
60 *
61 * json.publish(&quot;./data/some_player_database.json&quot;);
62 * </pre>
63 *
64 * @author lare96 <http://github.org/lare96>
65 */
66public final class JsonSaver {
67
72 private final Gson serializer = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create();
73
77 private final JsonArray array = new JsonArray();
78
82 private final boolean singletonTable;
83
88 private JsonObject currentWriter = new JsonObject();
89
94 public JsonSaver() {
95 this(false);
96 }
97
104 public JsonSaver(boolean singletonTable) {
105 this.singletonTable = singletonTable;
106 }
107
108 /***
109 * Gets the current {@code JsonObject} that is writing data.
110 *
111 * @return the current writer.
112 */
113 public JsonObject current() {
114 return currentWriter;
115 }
116
124 public void publish(String path) {
125 try (FileWriter fw = new FileWriter(path)) {
126 fw.write(toString());
127 } catch (final Exception e) {
128 e.printStackTrace();
129 }
130 }
131
137 public Gson serializer() {
138 return serializer;
139 }
140
150 public void split() {
151 Preconditions.checkState(!singletonTable, "JsonSaver instance is a singleton table!");
152 array.add(currentWriter);
153 currentWriter = new JsonObject();
154 }
155
166 @Override
167 public String toString() {
168 if (singletonTable) {
169 return serializer.toJson(currentWriter);
170 }
171 if (currentWriter.entrySet().size() > 0) {
172 split();
173 }
174 return serializer.toJson(array);
175 }
176}