Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
154 views
in Technique[技术] by (71.8m points)

java - How to sort GSON Array based on a key?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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());

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...