Skip to content

Commit 1981d4b

Browse files
author
Aleksey Genus
committed
Sort by keys inside json arrays
1 parent b290d8c commit 1981d4b

File tree

1 file changed

+25
-7
lines changed

1 file changed

+25
-7
lines changed

lib/src/gson/java/com/diffplug/spotless/glue/gson/GsonFormatterFunc.java

Lines changed: 25 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121

2222
import com.google.gson.Gson;
2323
import com.google.gson.GsonBuilder;
24+
import com.google.gson.JsonArray;
2425
import com.google.gson.JsonElement;
2526
import com.google.gson.JsonObject;
2627
import com.google.gson.stream.JsonWriter;
@@ -57,8 +58,8 @@ public String apply(String inputString) {
5758
if (jsonElement == null) {
5859
throw new AssertionError(FAILED_TO_PARSE_ERROR_MESSAGE);
5960
}
60-
if (gsonConfig.isSortByKeys() && jsonElement.isJsonObject()) {
61-
jsonElement = sortByKeys(jsonElement.getAsJsonObject());
61+
if (gsonConfig.isSortByKeys()) {
62+
jsonElement = sortByKeys(jsonElement);
6263
}
6364
try (StringWriter stringWriter = new StringWriter()) {
6465
JsonWriter jsonWriter = new JsonWriter(stringWriter);
@@ -72,19 +73,36 @@ public String apply(String inputString) {
7273
return result;
7374
}
7475

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+
7586
private JsonElement sortByKeys(JsonObject jsonObject) {
7687
JsonObject result = new JsonObject();
7788
jsonObject.keySet().stream().sorted()
7889
.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);
8492
});
8593
return result;
8694
}
8795

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+
88106
private String generateIndent(int indentSpaces) {
89107
return String.join("", Collections.nCopies(indentSpaces, " "));
90108
}

0 commit comments

Comments
 (0)