简体   繁体   中英

Sort Json based on multiple values

In Java, I want to sort my JSON objects (not a JSON array) based on multiple values. Below is an example of input JSON file content.

{"Name":"John","Age":27,"Gender":"Male"}
{"Name":"Lynda","Age":42,"Gender":"Female"}
{"Name":"Peter","Age":34,"Gender":"Male"}
{"Name":"Sheebha","Age":23,"Gender":"Female"}

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

{"Name":"John","Age":27,"Gender":"Male"}
{"Name":"Peter","Age":34,"Gender":"Male"}
{"Name":"Sheebha","Age":23,"Gender":"Female"}
{"Name":"Lynda","Age":42,"Gender":"Female"}

I am using GSON to parse the JSON. I just want an approach to do it. I am able to find solutions to sort a JSON array, but couldn't find one for objects.

Also, let me know the best API to parse JSON; GSON or JSON.simple or anything else.

You should essentially have a comparator method like this, in your POJO object.

public int compareTo(Object obj) {
    if(obj == null)
            return 1;
    else if (obj instanceof Person)
    {
        Person p2 = (Person) obj;
        if(this.gender.compareTo(p2.gender) < 0)
            return 1;
        else if(this.gender.compareTo(p2.gender) == 0)
            return this.age.compareTo(p2.age);
        else
            return -1;
    }
    else return 1;

}

It will sort first on the basis of Gender and then age, this is what I understand from your sample output.

From your JSON object convert to POJO object like this.

List<Person> personList = new ArrayList<>();
Person p =new GSON().fromJson(String , yourPOJO.class); // do this for all inputs
personList.add(p);

then you need to sort using

Collections.sort(personList);

hope this helps!

Good luck!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM