TerrificTable55

Untitled

Nov 14th, 2022
880
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.32 KB | None | 0 0
  1.  
  2. package com.arsenicclient.utils.io;
  3.  
  4. import com.google.gson.Gson;
  5. import com.google.gson.JsonElement;
  6. import com.google.gson.JsonObject;
  7.  
  8. import java.util.ArrayList;
  9.  
  10. public class JsonUtils {
  11.  
  12.     public static String jsonObjectToString(JsonObject in) {
  13.         return in.getAsString();
  14.     }
  15.  
  16.     public static JsonObject stringToJsonObject(String in) {
  17.         return new Gson().fromJson(in, JsonObject.class);
  18.     }
  19.  
  20.     public static ArrayList<String> jsonObjectToStringArrayList(JsonObject in) {
  21.         ArrayList<String> res = new ArrayList<>();
  22.  
  23.         for (JsonElement jsonElm : in.getAsJsonArray()) {
  24.             System.out.println(jsonElm);
  25.             res.add(jsonElm.toString());
  26.         }
  27.  
  28.         return res;
  29.     }
  30.  
  31.     public static String formatJsonObjectToString(JsonObject jsonObject) {
  32.         if (jsonObject.isJsonNull() || jsonObject.equals(new JsonObject())) return "{ }";
  33.  
  34.         String gson_obj = new Gson().toJson(jsonObject);
  35.         StringBuilder sb = new StringBuilder();
  36.         int indent = 0;
  37.         for (int i = 0; i < gson_obj.length(); i++) {
  38.             char c = gson_obj.charAt(i);
  39.             if (c == '{') {
  40.                 sb.append(c);
  41.                 if (gson_obj.charAt(i + 1) == '}')
  42.                     sb.append(" ");
  43.                 else {
  44.                     sb.append("\n");
  45.                     indent++;
  46.                     for (int j=0; j < indent; j++)
  47.                         sb.append("\t");
  48.                 }
  49.             } else if (c == '}') {
  50.                 if (gson_obj.charAt(i - 1) != '{') {
  51.                     sb.append("\n");
  52.                     indent--;
  53.                     for (int j=0; j < indent; j++)
  54.                         sb.append("\t");
  55.                 }
  56.                 sb.append(c);
  57.             } else if (c == ',') {
  58.                 sb.append(c);
  59.                 sb.append("\n");
  60.                 for (int j=0; j < indent; j++)
  61.                     sb.append("\t");
  62.             } else if (c == ':') {
  63.                 sb.append(c);
  64.                 sb.append(" ");
  65.             } else {
  66.                 sb.append(c);
  67.             }
  68.         }
  69.         return sb.toString();
  70.     }
  71.  
  72.     public static String formatJsonString(String jsonString) {
  73.         return formatJsonObjectToString(stringToJsonObject(jsonString));
  74.     }
  75.  
  76. }
  77.  
Advertisement
Add Comment
Please, Sign In to add comment