Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort my ojects which are parsed from json data

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

like image 215
john123 Avatar asked Dec 19 '12 14:12

john123


2 Answers

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

like image 101
Charlie Martin Avatar answered Oct 01 '22 14:10

Charlie Martin


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);
like image 29
Aleks G Avatar answered Oct 01 '22 15:10

Aleks G