2012-09-11 79 views
0

在我的應用程序中,下面的類接收一個JSONArray並使用它的數據來填充一個ListView。我希望這個ListView中的字段以字母順序出現。所以我想在使用它的數據之前對我的JSONArray進行排序。排序JSONArray沒有Gson,傑克遜等

我已經看到一些話題建議使用GSON或傑克遜,但我試圖以更簡單的方式做到這一點。我對這些庫不太瞭解,也沒有在他們的教程中找到我需要的東西。

的JSON的一個例子:

{"0":["1","Alimentos e Bebidas","Y"],"1":["6","Beleza e Cosm\u00e9ticos","Y"],"2": 
["11","Cama, Mesa e Banho","Y"],"3":["3","CDs, DVDs e Games","Y"],"4":["2","Convites 
e Cortesias","Y"],"5":["23","Cursos","Y"],"6":["8","Eletr\u00f4nicos","Y"],"7": 
["16","Esporte e Lazer","Y"],"8":["14","Inform\u00e1tica e Acess\u00f3rios","Y"], 
"9":["10","Limpeza","Y"],"10":["4","Livros","Y"],"11":["21","Livros no Sebo","Y"], 
"12":["5","Outros","Y"],"13":["12","Roupas e Acess\u00f3rios","Y"]} 

類方法,其中,我填充列表並等待用戶:

public void proccess(){ 
    listview = (ListView) findViewById(R.id.include3); 

    int qtdCategorias = json.length(); 
    categorias = new String[qtdCategorias]; 
    itens = new ArrayList<ItemListView>(); 
    for (int i=0; i<qtdCategorias; i++){ 
     c = json.optJSONArray(i); 
     String nomeCategoria = null; 
     try { 
      nomeCategoria = c.getString(1); //A consulta SQL do php retorna somente categorias habilitadas 
     } catch (JSONException e) { 
      Log.e("CategoriasShoppingActivity", e.toString()); 
      e.printStackTrace(); 
     } 
     categorias[i] = nomeCategoria; 
     //ItemListView item = new ItemListView(nomeCategoria); 
     //itens.add(item); 
    } 

    Arrays.sort(categorias); 

    for (int i=0; i<qtdCategorias; i++){ 
     ItemListView item = new ItemListView(categorias[i]); 
     itens.add(item); 
    } 


    adapterListView = new AdapterListView(this, itens); 
    listview.setAdapter(adapterListView); 


    listview.setOnItemClickListener(new OnItemClickListener() { 
     public void onItemClick(AdapterView<?> parent, View v, 
       int position, long id) { 
      c = json.optJSONArray(position); 
      String name = null; 
      String idt = null; 
      try { 
       name = c.getString(1); 
       idt = c.getString(0); 
      } catch (JSONException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } 

      Intent in = new Intent(getApplicationContext(), ProdutosActivity.class); 
      in.putExtra(TAG_NAME, name); 
      in.putExtra(TAG_ID, idt); 
      startActivity(in); 
     } 
    }); 




    } 

[編輯] 要請求從服務器數據,我使用這個JSONParser類():

public class JSONParser{ 

static InputStream is = null; 
static JSONArray jArr = null; 
static JSONStringer jArrString = null; 
static String json = ""; 
private static Context context; 
private ProgressDialog loader; 

// static HttpEntity httpEntity = null; 

// constructor 
public JSONParser() { 


} 



public JSONArray getJSONFromUrl(String url, List<NameValuePair> params) { 

    // Making HTTP request 
    try { 
     // defaultHttpClient 
     HttpClient httpClient = new DefaultHttpClient(); 
     HttpPost httpPost = new HttpPost(url); 
     httpPost.setEntity(new UrlEncodedFormEntity(params)); 



     HttpResponse httpResponse = httpClient.execute(httpPost); 
     HttpEntity httpEntity = httpResponse.getEntity(); 



     // json = EntityUtils.toString(httpEntity); 
     // HttpEntity httpEntity2 = httpEntity; 
     json = EntityUtils.toString(httpEntity); 
     // is = httpEntity.getContent(); 

    } catch (UnsupportedEncodingException e) { 
     e.printStackTrace(); 
    } catch (ClientProtocolException e) { 
     e.printStackTrace(); 
    } catch (IOException e) { 
     Log.e("JSONParser", "IOException "+e.toString()); 
     e.printStackTrace(); 
    } 

    try { 

     char[] c = new char[json.length()]; 
     json.getChars(0, json.length(), c, 0); 
     int i = 0; 
     while (c[i] == '\u00EF' || c[i] == '\u00BB' || c[i] == '\u00BF') { // remove 
                      // utf-8 
                      // BOM 
      i++; 
     } 
     json = json.substring(i); 


     Log.e("JSON", json); 
    } catch (Exception e) { 
     Log.e("Buffer Error", "Error converting result " + e.toString()); 
    } 

    // try parse the string to a JSON object 
    try { 
     JSONObject json_data = new JSONObject(json); 
     JSONArray hashMap_names = json_data.names(); 
     JSONArray hashMap_names2 = new JSONArray(); 
     Map hashMap = new HashMap(json_data.length()); 
     for (int i = 0; i != hashMap_names.length(); i++) { 
      hashMap.put(String.valueOf(i), json_data.get(String.valueOf(i))); 
      hashMap_names2.put(String.valueOf(i)); 
     } 
     JSONObject hashMap_obj = new JSONObject(hashMap); 

     jArr = hashMap_obj.toJSONArray(hashMap_names2); 

     // jArr = new JSONArray(json); 
     Log.e("JSON Parser", "succesful parsing data " + jArr.toString()); 
    } catch (Exception e) { 
     Log.e("JSON Parser", "Error parsing data " + e.toString()); 
     jArr = null; 
    } 

    // return JSON String 
    return jArr; 

} 

而在這裏,我收到我的班級的JSON

protected void onActivityResult(int requestCode, int resultCode, Intent data){ 
    if (requestCode == 1){ 
     if (resultCode == RESULT_OK){ 
      try { 
       json = new JSONArray(data.getStringExtra(TAG_JSON)); 
       Log.e("CategoriasShoppingActivity", "JSON: "+json); 
      } catch (JSONException e) { 
       e.printStackTrace(); 
      } 
      proccess(); 
     }else{ // resultCode == RESULT_CANCELED 
      Log.d("CategoriasJogarActivity", "AsyncTaskActicity retornou RESULT_CANCELED"); 
      finish(); 
     } 
    } 
} 

回答

0

爲什麼不在序列化之前對它進行排序?使用Comparator接口並使用Collections.sort對其進行排序。在排序時通過比較器作爲參數

+0

我看到了一些建議這種方法的主題(http://stackoverflow.com/questions/4277715/how-to-sort-json-object-in-java http://stackoverflow.com/questions/11121570/how-can-i-sort-nested-json-array)但是我無法理解他們的代碼。你能告訴我一個如何使用集合的例子嗎? –

+0

我用更多的代碼編輯了我的問題,也許現在更清晰 –

+1

看看http://www.mkyong.com/java/java-object-sorting-example-comparable-and-comparator/ – Chris

1

如果您有權訪問服務器端代碼,那麼在那裏排序列表會更容易。如果不是的話,你唯一的方法就是將它解析爲ArrayList,並使用任何已知的算法對其進行排序。

+0

的第4部分即時消息我的服務器上的SQL查詢我已經有了「order by:description」...我猜JSON不能保證它的元素的順序,這就是爲什麼我在我的應用程序中按順序收到它。馬我錯了嗎? –

+0

@Lucas Jota:與任何其他數組一樣,JSON數組肯定是排序的(用任何理性的語言)。什麼沒有排序是你的對象中的項目。你可能是對的,沒有這樣的保證。在你的代碼中,我看不到你是如何生成它的......你不能寫一個簡短的自包含的例子嗎? – maaartinus

+0

我用更多的代碼編輯了我的問題,也許現在更清楚了 –