2013-10-23 19 views
13

如何按对象字段对JSONArray对象进行排序?如何在JAVA中对JSONArray进行排序

输入:

[ 
    { "ID": "135", "Name": "Fargo Chan" }, 
    { "ID": "432", "Name": "Aaron Luke" }, 
    { "ID": "252", "Name": "Dilip Singh" } 
]; 

所需的输出(由 “名称” 字段排序):

[ 
    { "ID": "432", "Name": "Aaron Luke" }, 
    { "ID": "252", "Name": "Dilip Singh" } 
    { "ID": "135", "Name": "Fargo Chan" }, 
]; 
+0

我想根据“名称”进行排序。输出应该是: 432 Aaron Luke 252 Dilip Singh 135 Fargo Chan – kumarhimanshu449

回答

41

试试这个:

//I assume that we need to create a JSONArray object from the following string 
    String jsonArrStr = "[ { \"ID\": \"135\", \"Name\": \"Fargo Chan\" },{ \"ID\": \"432\", \"Name\": \"Aaron Luke\" },{ \"ID\": \"252\", \"Name\": \"Dilip Singh\" }]"; 

    JSONArray jsonArr = new JSONArray(jsonArrStr); 
    JSONArray sortedJsonArray = new JSONArray(); 

    List<JSONObject> jsonValues = new ArrayList<JSONObject>(); 
    for (int i = 0; i < jsonArr.length(); i++) { 
     jsonValues.add(jsonArr.getJSONObject(i)); 
    } 
    Collections.sort(jsonValues, new Comparator<JSONObject>() { 
     //You can change "Name" with "ID" if you want to sort by ID 
     private static final String KEY_NAME = "Name"; 

     @Override 
     public int compare(JSONObject a, JSONObject b) { 
      String valA = new String(); 
      String valB = new String(); 

      try { 
       valA = (String) a.get(KEY_NAME); 
       valB = (String) b.get(KEY_NAME); 
      } 
      catch (JSONException e) { 
       //do something 
      } 

      return valA.compareTo(valB); 
      //if you want to change the sort order, simply use the following: 
      //return -valA.compareTo(valB); 
     } 
    }); 

    for (int i = 0; i < jsonArr.length(); i++) { 
     sortedJsonArray.put(jsonValues.get(i)); 
    } 

排序后的JSONArray现在存储在sortedJsonArray目的。

+0

感谢您的回答。帮助很多。 –

+0

感谢您的回答。最后我不需要for循环。 – user3079872

+0

我知道这个工作,但它是可怕的,我们不得不诉诸这样的事情重用排序函数知道JsonArray包含项目作为集合'私人最终列表 elements',但私人! –

相关问题