Sort objects in json file (Java)

Asked

Viewed 407 times

0

I have the following JSON file:

{"idAluno":1,"nomeAluno":"Teste","listaDeTurmas":[1,2,3,4]}
{"idAluno":4,"nomeAluno":"Teste","listaDeTurmas":[1,2,3,4]}
{"idAluno":3,"nomeAluno":"Teste","listaDeTurmas":[1,2,3,4]}
{"idAluno":5,"nomeAluno":"Teste","listaDeTurmas":[1,2,3,4]}
{"idAluno":2,"nomeAluno":"Teste","listaDeTurmas":[1,3,4]}

I am using the Gson library in Java. It is possible to sort these records increasing in the file based on the "idAluno field"?

2 answers

0


Yes, it is possible.

Just have your class use the interface Comparable. In this interface, you will define the comparison criteria.

So you can add your elements to a collection that supports sorting, and use the method Collections.sort(testList); or Collections.reverse(testList);, depending on the desired order. Example - Collections.sort(testList, (a, b) -> b.compareTo(a));

  • Yes, but I would have to deserialize the Json string for an object and use, for example, an Arraylist to sort it, right? There is no way to sort the json file directly, without deserializing the string?

  • Then you can’t... you need to deserialize to do anything with the data.

  • Okay. Thank you!

-1

Here is an example where it was necessary to sort the json by the boolean value attribute.

Details of the command

parkingPlaces = lista de estacionamentos.
.stream().sorted = criar strem e comando de ordenacao
ParkingPlacesResponse.ParkingPlace = classe de objeto.
::getCloser = valor booleano que estou a ordenar.
.reversed() = sem ele o False fica no topo da lista.
.collect(Collectors.toList()) = finaliza a ordenacao inserindo em uma nova lista

For JAVA 8+

Upshot:

parkingPlaces.stream().sorted(Comparator.comparing(ParkingPlacesResponse.ParkingPlace::getCloser).reversed()).collect(Collectors.toList());

Browser other questions tagged

You are not signed in. Login or sign up in order to post.