21
21
22
22
import com .google .gson .Gson ;
23
23
import com .google .gson .GsonBuilder ;
24
+ import com .google .gson .JsonArray ;
24
25
import com .google .gson .JsonElement ;
25
26
import com .google .gson .JsonObject ;
26
27
import com .google .gson .stream .JsonWriter ;
@@ -57,8 +58,8 @@ public String apply(String inputString) {
57
58
if (jsonElement == null ) {
58
59
throw new AssertionError (FAILED_TO_PARSE_ERROR_MESSAGE );
59
60
}
60
- if (gsonConfig .isSortByKeys () && jsonElement . isJsonObject () ) {
61
- jsonElement = sortByKeys (jsonElement . getAsJsonObject () );
61
+ if (gsonConfig .isSortByKeys ()) {
62
+ jsonElement = sortByKeys (jsonElement );
62
63
}
63
64
try (StringWriter stringWriter = new StringWriter ()) {
64
65
JsonWriter jsonWriter = new JsonWriter (stringWriter );
@@ -72,19 +73,36 @@ public String apply(String inputString) {
72
73
return result ;
73
74
}
74
75
76
+ private JsonElement sortByKeys (JsonElement jsonElement ) {
77
+ if (jsonElement .isJsonArray ()) {
78
+ return sortByKeys (jsonElement .getAsJsonArray ());
79
+ } else if (jsonElement .isJsonObject ()) {
80
+ return sortByKeys (jsonElement .getAsJsonObject ());
81
+ } else {
82
+ return jsonElement ;
83
+ }
84
+ }
85
+
75
86
private JsonElement sortByKeys (JsonObject jsonObject ) {
76
87
JsonObject result = new JsonObject ();
77
88
jsonObject .keySet ().stream ().sorted ()
78
89
.forEach (key -> {
79
- JsonElement element = jsonObject .get (key );
80
- if (element .isJsonObject ()) {
81
- element = sortByKeys (element .getAsJsonObject ());
82
- }
83
- result .add (key , element );
90
+ JsonElement sorted = sortByKeys (jsonObject .get (key ));
91
+ result .add (key , sorted );
84
92
});
85
93
return result ;
86
94
}
87
95
96
+ private JsonElement sortByKeys (JsonArray jsonArray ) {
97
+ var result = new JsonArray ();
98
+ for (JsonElement element : jsonArray ) {
99
+ JsonElement sorted = sortByKeys (element );
100
+ result .add (sorted );
101
+ }
102
+
103
+ return result ;
104
+ }
105
+
88
106
private String generateIndent (int indentSpaces ) {
89
107
return String .join ("" , Collections .nCopies (indentSpaces , " " ));
90
108
}
0 commit comments