How to Sort JSON Array from JSON Objects in Android?

前端 未结 5 1967
醉话见心
醉话见心 2020-12-10 19:25

I have a JSON array, and I want to sort it Depending on the name and too alphabetically. My Json is as follows.

[
    {
        \"UserID\": 77,
        \"Inv         


        
5条回答
  •  没有蜡笔的小新
    2020-12-10 20:05

    Convert JSONArray to Arraylist and use Collections to sort your arraylist

    for example :

    ArrayList array = new ArrayList();
    JSONArray jsonArray = new JSONArray();
    for (int i = 0; i < jsonArray.length(); i++) {
        try {
            array.add(jsonArray.getJSONObject(i));
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    
    Collections.sort(array, new Comparator() {
    
        @Override
        public int compare(JSONObject lhs, JSONObject rhs) {
            // TODO Auto-generated method stub
    
            try {
                return (lhs.getString("Name").toLowerCase().compareTo(rhs.getString("Name").toLowerCase()));
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                return 0;
            }
        }
    });
    

提交回复
热议问题