java - Sorting an arraylist of jsonobjects on a particular json element -
i have written code creates array list of json info using gson library looks this.
{ "filename": "somefile.mp3" "artist": "artist1" "title": "title1" "genre": "rock" } { "filename": "anotherfile.mp3" "artist": "artist2" "title": "title2" "genre": "electro" }
im trying figure out how can sort array list artist element. ordering in way created via filename. reading on stackoverflow suggests should trying utilize custom comparator. ive been looking @ reply (how sort gson array based on key?) not working me.
i have custom class called tracks.class has getters , setters set holding title,artist,genre etc
trackfilemanager.class serializer , jsonobject.addproperty code , returns jsonobject mainactivity.
this jsonobject gets added arraylist called values below in mainactivity. (listoffiles array list holds filenames of mp3s)
final gsonbuilder gsonbuilder = new gsonbuilder(); gsonbuilder.registertypeadapter(track.class, new trackfilemanager()); gsonbuilder.setprettyprinting(); //diasablehtmlescaping stops & turning \u0026 final gson gson = gsonbuilder.disablehtmlescaping().create(); values = new arraylist<string>(); (string file : listoffiles){ t = new track(path,file); values.add(gson.tojson(t)); } collections.sort(values, new myjsoncomparator());
the other code have myjsoncomparator.class below
public class myjsoncomparator implements comparator<string> { @override public int compare(string s1, string s2) { homecoming s1.compareto(s2); } }
this produces no errors doesnt sort know wont way not hint errors in android studio. if alter code implements comparator<track>
collections.sort
produces error. , unless have comparator can't access elements want sort on s1.getartist
etc unless thats not right way it?? i've tried arraylist<string>
, pretty much other combinations of types except 1 works.
im doing wrong, im pretty sure im there. can help or @ to the lowest degree point me in right direction?
edit
public class myjsoncomparator implements comparator<track> { @override public int compare(track s1, track s2) { homecoming s1.artist.compareto(s2.artist); } }
the above code causes collections.sort(values,new myjsoncomparator());
error.
sort (list<string>, java.util.comparator<? super java.lang.string> in collections cannot applied arraylist<string>, com.example.myjsoncomparator.
your compare function should take objects input
@override public int compare(object s1, object s2) { homecoming s1.artist.compareto(s2.artist); }
collection.sort work on list ,having objects implementing same comparator interface.
refer below link http://www.programcreek.com/2011/12/examples-to-demonstrate-comparable-vs-comparator-in-java/
java android json arraylist gson
No comments:
Post a Comment