Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort GSON Array based on a key?

Tags:

java

sorting

gson

Consider the following is my Array

[
  {"id":10,"name":"name10","valid":true},
  {"id":12,"name":"name12","valid":false},
  {"id":11,"name":"name11","valid":false},
  {"id":9,"name":"name9","valid":true}
]

Created a JsonArray out of it, like following code does:

//Create a JSON Parser using GSON library 
objJsonParser = new JsonParser();
String strArrayText = [{"id":9,"name":"name9","valid":true}, ...]
JsonArray jsonArrayOfJsonObjects = objJsonParser.parse(strArrayText).getAsJsonArray();

Now, I am trying to sort jsonArrayOfJsonObjects based on name field.

Desired Output:

[
  {"id":9,"name":"name9","valid":true},
  {"id":10,"name":"name10","valid":false},
  {"id":11,"name":"name11","valid":false},
  {"id":12,"name":"name12","valid":true}
]

Could anyone help to sort this out with best apporach with respect to Java & Gson?
Your inputs are greatly appreciated.

like image 597
Amol M Kulkarni Avatar asked Sep 02 '13 14:09

Amol M Kulkarni


1 Answers

First of all, the proper way to parse your JSON is to create a class to encapsulate your data, such as:

public class MyClass {
    private Integer id;
    private String name;
    private Boolean valid;
    //getters & setters
}

And then:

Type listType = new TypeToken<List<MyClass>>() {}.getType();
List<MyClass> myList = new Gson().fromJson(strArrayText, listType);

Now you have a List and you want to sort it by the value of the attribute id, so you can use Collections as explained here:

public class MyComparator implements Comparator<MyClass> {
    @Override
    public int compare(MyClass o1, MyClass o2) {
        return o1.getId().compareTo(o2.getId());
    }
}

And finally:

Collections.sort(myList, new MyComparator());
like image 92
MikO Avatar answered Oct 10 '22 23:10

MikO