5

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??

john123
  • 589
  • 3
  • 6
  • 16
  • 1
    Is there a reason not to just use [`Collections.sort()`](http://docs.oracle.com/javase/6/docs/api/java/util/Collections.html#sort%28java.util.List%29)? – amit Dec 19 '12 at 15:02
  • I'm not familiar with java. But I don't think you sorted the list. Try call the Collections.sort(students)? – Evan Dec 19 '12 at 15:05
  • you need to actually compare them... – njzk2 Dec 19 '12 at 15:57

3 Answers3

5

Simply implementing Comparable won't make your class be sorted; you've got to actually do something to sort it.

Charlie Martin
  • 110,348
  • 25
  • 193
  • 263
2

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);
Aleks G
  • 56,435
  • 29
  • 168
  • 265
1

Just because your class is Comparable does not make every collection automatically sort itself. You have to tell a particular collection to sort using the natural orderering, by using something like Collections.sort(students);

Thorn G
  • 12,620
  • 2
  • 44
  • 56