How to sort GSON Array based on a key?

后端 未结 3 714
遇见更好的自我
遇见更好的自我 2020-12-10 07:29

Consider the following is my Array

[
  {\"id\":10,\"name\":\"name10\",\"valid\":true},
  {\"id\":12,\"name\":\"name12\",\"valid\":false},
  {\"id\":11,\"name         


        
3条回答
  •  无人及你
    2020-12-10 08:05

    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>() {}.getType();
    List 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 {
        @Override
        public int compare(MyClass o1, MyClass o2) {
            return o1.getId().compareTo(o2.getId());
        }
    }
    

    And finally:

    Collections.sort(myList, new MyComparator());
    

提交回复
热议问题