2012-10-15 57 views
18

我做了一個JSONObjects的jsonarray的JSONArray。現在我需要根據jsonobjects中的值對JSONArray進行排序。以前我整理這樣的自定義對象的ArrayList:的Android如何排序一個JSONObjects

比較:

public class KreeftenComparatorLA implements Comparator<Kreeft> { 
    public int compare(Kreeft left, Kreeft right) { 
     return left.latijnseNaam.compareTo(right.latijnseNaam); 
    } 
} 
public class KreeftenComparatorNL implements Comparator<Kreeft> { 
    public int compare(Kreeft left, Kreeft right) { 
     return left.naam.compareTo(right.naam); 
    } 
} 

然後排序的ArrayList:

Collections.sort(db.lijst, new KreeftenComparatorLA()); 

或:

Collections.sort(db.lijst, new KreeftenComparatorNL()); 

但是,當我嘗試與jSONArray像這樣(JA =我jSONArray),其中同樣的事情

Collections.sort(JA, new KreeftenComparatorNL()); 

的Collections.sort給出了一個錯誤:

The method sort(List, Comparator) in the type Collections is not applicable for the arguments (JSONArray, ThisActicity.KreeftenComparatorNL)

有誰知道如何JSONArray排序?

+0

http://stackoverflow.com/questions/4833084/is-there-any-easy-way-to-sort-可能的欺騙a-jsonarray-of-objects-by-an-attribute-in-android?rq = 1 – petey

+0

請考慮這一點:如果您可以在構建JsonArray之前進行排序,請執行此操作。您也可以稍後在JavaScript中對其進行排序。我認爲從JsonArray建立一個列表,排序列表,然後重建JsonArray是相當可怕的:) –

回答

34

的問題是,JSONArray或多或少保持一個JSONObjects(和其它JSONArrays),這最終是字符串。將字符串完全反序列化爲POJO,將這些字符串進行排序,然後重新導入到JSON中相當繁重。

的第二個問題是,JSONArray可以包含:布爾,JSONArray,JSONObject的,數字,字符串,或JSONObject.NULL對象;即,它是混合類型,使其難以只轉儲的元素爲若干類型和排序是,然後穿過該列表傾倒排序項回JSON陣列的列表。唯一確定的方式來獲得從JSONArray每個元素的常見類型是使用對象get()方法..當然,那麼所有你是Object對象,將不能夠做他們的任何有意義的排序沒有重溫序列化問題。

假設您的JSONArray包含同構結構的值,您可以遍歷JSONArray,調用每個類型的get()方法之一,將它們轉儲爲List類型,然後對其進行排序。如果你的JSONArray只是像String或者數字那樣擁有「簡單」類型,這相對容易。這不是確切的代碼,但類似:

List<String> jsonValues = new ArrayList<String>(); 
for (int i = 0; i < myJsonArray.length(); i++) 
    jsonValues.add(myJsonArray.getString(i)); 
Collections.sort(jsonValues); 
JSONArray sortedJsonArray = new JSONArray(jsonValues); 

當然,如果你有嵌套的對象,這可能會有點棘手。如果該值爲()你要作爲排序依據住在頂層,它可能不是洙壞...

List<JSONObject> jsonValues = new ArrayList<JSONObject>(); 
for (int i = 0; i < myJsonArray.length(); i++) 
    jsonValues.add(myJsonArray.getJSONObject(i)); 

然後用一個比較像這樣的排序:

class JSONComparator implements Comparator<JSONObject> 
{ 

    public int compare(JSONObject a, JSONObject b) 
    { 
     //valA and valB could be any simple type, such as number, string, whatever 
     String valA = a.get("keyOfValueToSortBy"); 
     String valB = b.get("keyOfValueToSortBy"); 

     return valA.compareTo(valB); 
     //if your value is numeric: 
     //if(valA > valB) 
     // return 1; 
     //if(valA < valB) 
     // return -1; 
     //return 0;  
    } 
} 

再次,這會對您的JSONArray中的數據的同質性​​做出一些假設。儘可能調整你的情況。你也需要添加你的異常處理等。快樂編碼!

編輯 固定根據意見

+0

更新行Collections.sort(jsonValues); –

+2

這個例子很接近,但不能編譯。由於Java沒有運算符重載這一事實,您無法比較這種方式。該示例應該返回valA.compareTo(valB)。 – SoWeLie

8

只是要清楚上面的代碼進行排序比較是不正確的。 像Ruby一樣,你無法像上面那樣比較字符串。 這可以寫得更簡潔如下。否則,邏輯是健全的。

Collections.sort(jsonValues, new Comparator<JSONObject>() { 
    @Override 
    public int compare(JSONObject a, JSONObject b) { 
     String valA = new String(); 
     String valB = new String(); 

     try { 
      valA = (String) a.get("keyOfValueToSortBy"); 
      valB = (String) b.get("keyOfValueToSortBy"); 
     } 
     catch (JSONException e) { 
      Log.e(LOG_TAG, "JSONException in combineJSONArrays sort section", e); 
     } 

     return valA.compareTo(valB); 
    } 
}); 
+1

難道你只是返回valA.compareTo(valB)? – SoWeLie

+1

是的,你是對的,如果...返回是不必要的。 –

8

爲了填寫Android列表ArrayAdapter我需要做到這一點。這是我做的:

活動代碼從一個JSONArray建立一個列表:

JSONArray kids = node.getJSONArray("contents"); 
kids = JSONUtil.sort(kids, new Comparator(){ 
    public int compare(Object a, Object b){ 
     JSONObject ja = (JSONObject)a; 
     JSONObject jb = (JSONObject)b; 
     return ja.optString("name", "").toLowerCase().compareTo(jb.optString("name", "").toLowerCase(); 
    } 
}); 
// in my case I wanted the original larger object contents sorted... 
node.put("contents", kids); 

而且在JSONUtil(我的助手):

public static JSONArray sort(JSONArray array, Comparator c){ 
    List asList = new ArrayList(array.length()); 
    for (int i=0; i<array.length(); i++){ 
     asList.add(array.opt(i)); 
    } 
    Collections.sort(asList, c); 
    JSONArray res = new JSONArray(); 
    for (Object o : asList){ 
     res.put(o); 
    } 
    return res; 
} 
+0

也許這在適配器本身:http://stackoverflow.com/a/32213875/383761 –

1

一個例子與Date領域:

public class JsonObjectComparator implements Comparator<JSONObject> { 
private final String fieldName; 
private Class<? extends Comparable> fieldType; 

public JsonObjectComparator(String fieldName, Class<? extends Comparable> fieldType) { 
    this.fieldName = fieldName; 
    this.fieldType = fieldType; 
}  

@Override 
public int compare(JSONObject a, JSONObject b) { 
    String valA, valB; 
    Comparable newInstance_valA, newInstance_valB; 
    int comp = 0; 
    try { 
     Constructor<? extends Comparable> constructor = fieldType.getConstructor(String.class);    
     valA = a.getString(fieldName); 
     valB = b.getString(fieldName); 
     if (fieldType.equals(Date.class)) { 
      SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy"); 
      newInstance_valA = dateFormat.parse(valA);    
      newInstance_valB = dateFormat.parse(valB); 
     } else { 
      newInstance_valA = constructor.newInstance(valA);    
      newInstance_valB = constructor.newInstance(valB); 
     } 
     comp = newInstance_valA.compareTo(newInstance_valB); 
    } catch (Exception e) { 
     System.out.println(e.getMessage()); 
    } 

    if(comp > 0) 
     return 1; 
    if(comp < 0) 
     return -1; 
    return 0; 
    } 

} 

public static void main(String[] args) throws JSONException {   
    JSONObject o1 = new JSONObject(); 
    o1.put("key1", "26-06-2014"); 
    JSONObject o2 = new JSONObject(); 
    o2.put("key1", "30-11-2011"); 
    JSONObject o3 = new JSONObject(); 
    o3.put("key1", "15-07-2014"); 

    JsonObjectComparator comparator = new JsonObjectComparator("key1", Date.class); 
    List<JSONObject> l = new ArrayList<>(); 
    l.add(o1); 
    l.add(o2); 
    l.add(o3); 

    Collections.sort(l, comparator); 
} 
1

如果您要顯示JSONArray中包含的數據,那麼它在適配器本身中排序它可能是有意義的。例如,ArrayAdapter<T>類已經具有必要的方法,例如Insert,Remove,當然還有Sort

adapter.sort(new Comparator<JSONObject>(){ 

    @Override 
    public int compare(JSONObject arg0, JSONObject arg1) { 

     return arg0.optString("SortField", "").compareTo(arg1.optString("SortField","")) ; 

    } 

}); 
0
//My script 
//HEADER add final variables 
    private final int TYPE_STRING = 1; 
    private final int TYPE_INT = 2; 
    private final int TYPE_DUBLE = 3; 


//METHOD GET SORT JSONARRAY 
public JSONArray getSortJSONArray() 
{ 
JSONArray json = new JSONArray ([{"carid":"957502","vin":"XXXXX","carbrand":"CADILLAC","carmodel":"CTS","carname":"CADILLAC CTS седан CTS PERFORMANC 2.0L AWD AK4 2 4WD AT-6 276 (Л.С.)","carmodificationname":" седан CTS PERFORMANC 2.0L AWD AK4 2 4WD AT-6 276 (Л.С.)","carcolorname":"Opulent Blue Metallic - ярко-синий металлик","price":"3410000","rgb":"","volumereal":"2,00","power":"276"},{"carid":"957502","vin":"XXXXX","carbrand":"CADILLAC","carmodel":"CTS","carname":"CADILLAC CTS седан CTS PERFORMANC 2.0L AWD AK4 2 4WD AT-6 276 (Л.С.)","carmodificationname":" седан CTS PERFORMANC 2.0L AWD AK4 2 4WD AT-6 276 (Л.С.)","carcolorname":"Opulent Blue Metallic - ярко-синий металлик","price":"3460000","rgb":"","volumereal":"1,00","power":"272"}]"); 

/*halper - My halper */ 
    JSONArray sorJsonArray = halper.sort(json, getComparator("power",TYPE_INT)); 
    return sorJsonArray; 
} 

private Comparator getComparator(final String tagJSON,final int type) 
    { 
     Comparator c = new Comparator() 
     { 
      public int compare(Object a, Object b) 
      { 


       try 
       { 
        JSONObject ja = (JSONObject)a; 
        JSONObject jb = (JSONObject)b; 

        switch (type) 
        { 
         case TYPE_STRING:// String 
          return ja.optString(tagJSON, "") 
               .toLowerCase() 
               .compareTo(jb.optString(tagJSON, "").toLowerCase()); 
         case TYPE_INT:// int 
          int valA = ja.getInt(tagJSON); 
          int valB = jb.getInt(tagJSON); 
          if(valA > valB) 
           return 1; 
          if(valA < valB) 
           return -1; 

         case TYPE_DUBLE:// double 
          String v1 = ja.getString(tagJSON).replace(",","."); 
          String v2 = jb.getString(tagJSON).replace(",","."); 

          double valAd = new Double(v1);// ja.getDouble(tagJSON); 
          double valBd = new Double(v2);// jb.getDouble(tagJSON); 
          if(valAd > valBd) 
           return 1; 
          if(valAd < valBd) 
           return -1; 

        } 
       } 
       catch (Exception e) 
       { 
        e.printStackTrace(); 
       } 
       return 0; 
      } 
     }; 

     return c; 
    } 

//我哈爾波類

public class Halpe { 
    public void Halpe(){} 

    public static JSONArray sort(JSONArray array, Comparator c) 
    { 
     List asList = new ArrayList(array.length()); 
     for (int i=0; i<array.length(); i++){ 
      asList.add(array.opt(i)); 
     } 
     Collections.sort(asList, c); 
     JSONArray res = new JSONArray(); 
     for (Object o : asList){ 
      res.put(o); 
     } 
     return res; 
    }} 
相關問題