I am trying to sort a JsonArray in Java using GSON, I would like to sort everything inside that array via a variable key, meaning there is a string somewhere containing something that is the key that the object needs to be sorted by.
Key Variable: varkey1
[{"varkey1":1,"othervarkey":1},{"varkey1":6,"othervarkey":2},{"varkey1":3,"othervarkey":3},{"varkey1":12,"othervarkey":4},{"varkey1":998,"othervarkey":5}]
So it should go like like:
[{"varkey1":1,"othervarkey":1},{"varkey1":3,"othervarkey":2},{"varkey1":6,"othervarkey":3},{"varkey1":12,"othervarkey":4},{"varkey1":998,"othervarkey":5}]
Advertisement
Answer
Well, you could just implement a sorting algorithm that could be specialized for Gson JsonElement
s.
If not, you could just re-use standard Collections.sort(...)
that can merely do the job for you.
For some reason, JsonArray
implements Iterable
and not List
where the latter can be sorted with Collection.sort
.
So, a custom JsonArray
-to-List
is required:
final class JsonArrayList extends AbstractList<JsonElement> { private final JsonArray jsonArray; private JsonArrayList(final JsonArray jsonArray) { this.jsonArray = jsonArray; } static List<JsonElement> of(final JsonArray jsonArray) { return new JsonArrayList(jsonArray); } // This method is required when implementing AbstractList @Override public JsonElement get(final int index) { return jsonArray.get(index); } // This method is required when implementing AbstractList as well @Override public int size() { return jsonArray.size(); } // And this one is required to make the list implementation modifiable @Override public JsonElement set(final int index, final JsonElement element) { return jsonArray.set(index, element); } }
Now, the rest is simple:
// No even need of Gson instantiation final JsonArray jsonArray = new JsonParser() .parse(jsonReader) .getAsJsonArray(); // Create a JsonArray to a List view instance final List<JsonElement> jsonElements = JsonArrays.asList(jsonArray); // Sorting the jsonElements object Collections.sort(jsonElements, (e1, e2) -> { final int i1 = e1.getAsJsonObject().get("varkey1").getAsInt(); final int i2 = e2.getAsJsonObject().get("varkey1").getAsInt(); return Integer.compare(i1, i2); });
Since the jsonElements
is just a view for jsonArray
, jsonArray
is actually sorted.