• Post Reply Bookmark Topic Watch Topic
  • New Topic

Sort JSON based on multiple values  RSS feed

 
Padmanabhan Vijendran
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In Java, I want to sort my json objects (not a Json array) based on multiple values. For example, below is my input Json file content.



I need to sort these objects by Age and Gender. I need an output like below.

I am using GSON to parse the json. I just want an approach to do it. I am able to find the solutions to sort a json array. But couldnt find for objects.
 
Liutauras Vilda
Sheriff
Posts: 4916
334
BSD
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch.

Do you have defined Person class where you store parsed data?
You can implement couple of comparators, one which does sorting by age, another by gender.

An age comparator could look similar:
 
Liutauras Vilda
Sheriff
Posts: 4916
334
BSD
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Then there are Java 8 way, can you try to find how to do that? That would be way shorter and nicer solution.
 
Campbell Ritchie
Marshal
Posts: 56525
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I would suggest a slight change to that documentation comment:-Alternative version which maybe fits the specification for Comparator#compare() better:-That way you are not committing yourself to any specific return values, except 0 for both the same.

Padmanabhan Vijendran: Have a look in the Java™ Tutorials, where there is a good section about ordering objects. It will probably tell you all you need to know to solve your current problem. Assuming all elements in your file are marked Male or Female, you can create an enumerated type, and get the instance of the enum with the Enum#valueOf() method:-If you write the enum in UPPER CASE as one usually does, you will need the toUpperCase() call.


...and welcome again
 
Campbell Ritchie
Marshal
Posts: 56525
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Another way to get the enum instances from their names might be to use a Map<String, Gender>.
 
Knute Snortum
Sheriff
Posts: 4273
127
Chrome Eclipse IDE Java Postgres Database VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Two things  to keep in mind about this Javadoc.  First, the program javadoc doesn't like less than or greater than signs, so...

And  second, javadoc removes all whitespace, so if you want to format text, you will need  to use something  like an HTML unordered list...

I know this makes it harder to read as a human, but that's why I said, "Keep it in mind."  You'll have to decide what's more important.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!