Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter Json array

Tags:

java

json

android

This is my first time working with json and I'm having a hard time trying to filter an array I'm trying to get all values (tienda) where id_estado=1.

Any clue how to approach this?

JA1= [{"id_estado":"1","tienda":"Aurrera"},{"id_estado":"1","tienda":"Walt-Mart"},{"id_estado":"1","tienda":"Chedraui"},{"id_estado":"1","tienda":"Soriana"},{"id_estado":"1","tienda":"Comercial MX"},{"id_estado":"1","tienda":"City Market"},{"id_estado":"2","tienda":"Walt-Mart"},{"id_estado":"2","tienda":"Chedraui"},{"id_estado":"2","tienda":"Aurrera"},{"id_estado":"2","tienda":"Superama"}]

            JSONArray JA1=new JSONArray(result1);
        JSONObject json1= null;
        name = new String[JA1.length()];
            for (int i = 0; i < JA1.length(); i++) {
                 Log.d("LOG", "resultado name sin arreglo11 " + JA1);
                //name[i] = json1.getString("tienda");
                //name[i]=json1.getString("estado");
            }

        for(int i=0;i<name.length;i++)
        {
            list2.add(name[i]);
            Log.d("LOG", "resultado name2 " + name[i]);
        }

Thanks in advance

like image 861
Cesar Bellic Avatar asked Oct 29 '25 09:10

Cesar Bellic


1 Answers

Here's how I'd do it:

    try {
        List<String> filtered = new ArrayList<>();
        JSONArray ary = new JSONArray(/* your json here */);

        for (int i = 0; i < ary.length(); ++i) {
            JSONObject obj = ary.getJSONObject(i);
            String id = obj.getString("id_estado");
            if (id.equals("1")) {
                filtered.add(obj.getString("tienda"));
            }
        }
    } catch (JSONException e) {
        // handle exception
    }

An explanation of this code:

  • Create an ArrayList to hold the filtered values.
  • Create a JSONArray from your json text.
  • Iterate over each element in the array, pulling out a JSONObject each time.
  • For each object, we get its id_estado property and check if it is equal to "1".
  • If it is, we add the tienda property to the list of filtered values.
like image 63
Ben P. Avatar answered Oct 31 '25 00:10

Ben P.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!