Skip to content

Instantly share code, notes, and snippets.

@thasave14
Created September 9, 2024 19:15
Show Gist options
  • Save thasave14/c283cedeeedac7b9a0a917692cff1c89 to your computer and use it in GitHub Desktop.
Save thasave14/c283cedeeedac7b9a0a917692cff1c89 to your computer and use it in GitHub Desktop.
Simple Java utility to manage jsons easily without extra libraries
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
public class JSON {
private Map<String, Object> map;
private static String cached;
private JSON() {
this.map = new HashMap<>();
}
public Object get(String name) {
return map.get(name);
}
public void put(String name, Object value) {
map.put(name, value);
cached = null;
}
public static JSON fromJsonFile(File file) throws IOException {
try (BufferedReader buf = new BufferedReader(new InputStreamReader(new FileInputStream(file)))) {
StringBuilder builder = new StringBuilder();
String line;
while((line = buf.readLine()) != null) {
builder.append(line);
}
return fromJsonString(builder.toString());
}
}
public static JSON fromJsonString(String jsonString) {
JSON json = new JSON();
jsonString = jsonString.trim();
if (jsonString.startsWith("{") && jsonString.endsWith("}")) {
jsonString = jsonString.substring(1, jsonString.length() - 1).trim();
}
String[] keyValuePairs = jsonString.split(",(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)");
for (String pair : keyValuePairs) {
String[] entry = pair.split(":", 2);
String key = entry[0].trim().replaceAll("^\"|\"$", "");
String value = entry[1].trim();
if (value.startsWith("\"") && value.endsWith("\"")) {
json.put(key, value.substring(1, value.length() - 1));
} else if ("true".equals(value) || "false".equals(value)) {
json.put(key, Boolean.parseBoolean(value));
} else if ("null".equals(value)) {
json.put(key, null);
} else {
try {
json.put(key, value.contains(".") ? Double.parseDouble(value) : Integer.parseInt(value));
} catch (NumberFormatException e) {
json.put(key, value);
}
}
}
cached = json.toString();
return json;
}
private String formatValue(Object value) {
if (value instanceof String) {
return "\"" + value + "\"";
}
if (value instanceof JSON) {
return value.toString();
}
return String.valueOf(value);
}
@Override
public String toString() {
if(cached == null) {
StringBuilder json = new StringBuilder();
json.append("{");
int count = 0;
for (Map.Entry<String, Object> entry : map.entrySet()) {
json.append("\"").append(entry.getKey()).append("\": ");
json.append(formatValue(entry.getValue()));
count++;
if (count < map.size()) {
json.append(", ");
}
}
json.append("}");
cached = json.toString();
}
return cached;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment