Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class JsonUtils {
- /**
- * Read File contents into JsonObject
- * @param path path to a file that should be read
- * @return JsonObject with contents of file
- */
- public static JsonObject readJsonFile(String path) {
- String json = FileIOUtils.readFile(path);
- return convertStringToJsonObject(json);
- }
- /**
- * Converts String to JsonObject
- * @param json_str the Json String to be returned as JsonObject
- * @return JsonObject
- */
- public static JsonObject convertStringToJsonObject(String json_str) {
- return new Gson().fromJson(json_str, JsonObject.class);
- }
- public static ArrayList<String> jsonObjectToStringArrayList(JsonObject in) {
- ArrayList<String> res = new ArrayList<>();
- for (JsonElement jsonElm : in.getAsJsonArray()) {
- System.out.println(jsonElm);
- res.add(jsonElm.toString());
- }
- return res;
- }
- /**
- * prints out a test json object to test if json functions work
- * @param json the JsonObject to print out
- */
- public static void debug(JsonObject json) {
- if (NoWay.dev) { // only print if dev version
- System.out.println("Non Formatted: " + new Gson().toJson(json));
- System.out.println("Formatted: " + formatJsonObjectToString(json));
- System.out.println("Conv to JsonObj: " + convertStringToJsonObject(formatJsonObjectToString(json)).getClass() + " -> " + convertStringToJsonObject(formatJsonObjectToString(json)));
- }
- }
- /**
- * Format JsonObject
- * Input: {"a":"b","c":"d"}
- * Output: {
- * "a": "b",
- * "c": "d"
- * }
- *
- * @param jsonObject JsonObject input
- * @return JsonObject formatted and converted to String
- */
- public static String formatJsonObjectToString(JsonObject jsonObject) {
- if (jsonObject.isJsonNull() || jsonObject.equals(new JsonObject())) return "{ }";
- String gson_obj = new Gson().toJson(jsonObject);
- StringBuilder sb = new StringBuilder();
- int indent = 0;
- for (int i = 0; i < gson_obj.length(); i++) {
- char c = gson_obj.charAt(i);
- if (c == '{') {
- sb.append(c);
- if (gson_obj.charAt(i + 1) == '}')
- sb.append(" ");
- else {
- sb.append("\n");
- indent++;
- for (int j=0; j < indent; j++)
- sb.append("\t");
- }
- } else if (c == '}') {
- if (gson_obj.charAt(i - 1) != '{') {
- sb.append("\n");
- indent--;
- for (int j=0; j < indent; j++)
- sb.append("\t");
- }
- sb.append(c);
- } else if (c == ',') {
- sb.append(c);
- sb.append("\n");
- for (int j=0; j < indent; j++)
- sb.append("\t");
- } else if (c == ':') {
- sb.append(c);
- sb.append(" ");
- } else {
- sb.append(c);
- }
- }
- return sb.toString();
- }
- /**
- * String to json to formatJsonObjectToString(JsonObject)
- * @param jsonString String input
- * @return String output
- */
- public static String formatJsonString(String jsonString) {
- return formatJsonObjectToString(convertStringToJsonObject(jsonString));
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment