java - 不使用 Gson、Jackson 等对 JSONArray 进行排序

标签 java android json sorting gson

在我的应用程序中,下面的类接收 JSONArray 并使用其数据填充 ListView。我希望此 ListView 中的字段按字母顺序显示。所以我想在使用 JSONArray 的数据之前对其进行排序。

我看到一些主题建议使用 GSON 或 Jackson,但我正在尝试以更简单的方式做到这一点。我不太了解这些库,也没有在他们的教程中找到我需要的东西。

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;

}

在这里,我在类(class)中收到了 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();
        }
    }
}

最佳答案

如果您有权访问服务器端代码,那么在那里对列表进行排序会更容易。如果没有,唯一的方法是将其解析为 ArrayList 并使用任何已知的算法对其进行简单排序。

关于java - 不使用 Gson、Jackson 等对 JSONArray 进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12372590/

相关文章:

java - 如何在Java中检查hibernate session 连接是否处于只读模式

javascript - 如何在 HTML 中对同一个 div 进行多个不同的 AJAX 调用

Java 泽西网络服务 : consume JSON request

json - 使用 XSLT 编写 JSON

java - Jsoup 股票行情刮取雅虎财经

java - 这个DFS递归函数中的深度+1和深度++有什么区别?

java - 将对象添加到 ArrayList 并稍后对其进行修改

java - 如何在java(Excel)中写入特定列并读取特定列?

android - onViewStateRestored 崩溃的 Android 应用程序

运行线程时的Android刷新 Activity