My Android client get server JSON response as follows:
{"students":[{"id":1,"name":"John","age":12},
{"id":2,"name":"Thmas","age":13}
{"id":3,"name":"Merit","age":10}
...]}
My Android client code parses the JSON response to Java object by using gson.
My corresponding Java classes:
public class StudentList{
private List<Student> students;
public List<Student> getStudents(){
return students;
}
}
public class Student{
private long id;
private String name;
private int age;
public long getId() {
return id;
}
public String getName(){
return name;
}
public int getAge(){
return age;
}
}
Everything works fine for me at this point, I can successfully parse JSON data to my Java objects, like following:
//'jsonData' is the server responsed json data
StudentList students = gson.fromJson(jsonData, StudentList.class)
Then, I would like to modify a bit to get the students
(from json
data) in an alphabetic order, sorted by student's name
. I tried the following way: (I changed the Student
class to implement the Comparable<>
interface):
public class Student implements Comparable<Student>{
private long id;
private String name;
private int age;
public long getId() {
return id;
}
public String getName(){
return name;
}
public int getAge(){
return age;
}
// Override compareTo(), sort by 'name'
@Override
public int compareTo(Student obj) {
return this.getName().compareToIgnoreCase(obj.Name());
}
}
With above modified Student
class, I tried to parse the json data again :
//'jsonData' is the server responsed json data
StudentList students = gson.fromJson(jsonData, StudentList.class)
But the resulted students
are still the same as before the sorting. My sorting solution does not work at all. Why?? Where am I wrong??
gson will not sort items in the list, it will still just add the items. You can sort the list after it's created using Collections.sort
method:
java.util.Collections.sort(students);