JSON Pretty Print @param json @return @throws JSONException
(String json)
| 79 | * @throws JSONException |
| 80 | */ |
| 81 | public static String format(String json) { |
| 82 | try { |
| 83 | return (JSONUtil.format( |
| 84 | new JSONObject(json) { |
| 85 | /** |
| 86 | * changes the value of JSONObject.map to a LinkedHashMap in order to maintain order of |
| 87 | * keys. See Also: https://stackoverflow.com/a/62476486 |
| 88 | */ |
| 89 | @Override |
| 90 | public JSONObject put(String key, Object value) throws JSONException { |
| 91 | try { |
| 92 | Field map = JSONObject.class.getDeclaredField("map"); |
| 93 | map.setAccessible(true); |
| 94 | Object mapValue = map.get(this); |
| 95 | if (!(mapValue instanceof LinkedHashMap)) { |
| 96 | map.set(this, new LinkedHashMap<>()); |
| 97 | } |
| 98 | } catch (NoSuchFieldException | IllegalAccessException e) { |
| 99 | throw new RuntimeException(e); |
| 100 | } |
| 101 | return super.put(key, value); |
| 102 | } |
| 103 | })); |
| 104 | } catch (RuntimeException ex) { |
| 105 | throw ex; |
| 106 | } catch (Exception ex) { |
| 107 | throw new RuntimeException(ex); |
| 108 | } |
| 109 | } |
| 110 | |
| 111 | public static String format(JSONObject o) { |
| 112 | try { |