1package com.osroyale.util.parser;
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;
9import java.io.FileWriter;
46* A util
class used for constructing and writing {@code JSON} files.
49 * And an example of usage:
52 * JsonSaver json =
new JsonSaver();
54 *
for (Player player : players) {
55 * json.current().addProperty("name", player.getUsername());
56 * json.current().addProperty("value1", 1);
57 * json.current().addProperty("value2",
true);
61 * json.publish("./data/some_player_database.json");
64 * @author lare96 <http:
66public final class JsonSaver {
72 private final Gson serializer =
new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create();
77 private final JsonArray array =
new JsonArray();
82 private final boolean singletonTable;
88 private JsonObject currentWriter =
new JsonObject();
104 public JsonSaver(
boolean singletonTable) {
105 this.singletonTable = singletonTable;
113 public JsonObject current() {
114 return currentWriter;
124 public void publish(String path) {
125 try (FileWriter fw =
new FileWriter(path)) {
126 fw.write(toString());
127 }
catch (
final Exception e) {
137 public Gson serializer() {
150 public void split() {
151 Preconditions.checkState(!singletonTable,
"JsonSaver instance is a singleton table!");
152 array.add(currentWriter);
153 currentWriter =
new JsonObject();
167 public String toString() {
168 if (singletonTable) {
169 return serializer.toJson(currentWriter);
171 if (currentWriter.entrySet().size() > 0) {
174 return serializer.toJson(array);