2012-09-11 34 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

我用更多的代码编辑了我的问题,也许现在更清楚了 –